I am trying to run widgets on visionOS 26. Specifically I am trying to pin them to the simulator room's walls, however I am unable to do so.
Is this a limitation with the visionOS simulator right now, or am I missing a trick here?
WidgetKit
RSS for tagShow relevant, glanceable content from your app on iOS and iPadOS Home Screen and Lock Screen, macOS Desktop, Apple Watch Smart Stack and Complications, and in StandBy mode on iPhone.
Posts under WidgetKit tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Is SFSymbol Customization officially valid as a method for using SVG in embedded widgets (lock-screen & watchOS)?
I use this in UnitedPizzaHelper but wonder whether this is the prime cause why all widgets of this app gets missing on iOS devices? This issue only happened on at least 2 device in the recent 12 months (they are all on iOS 18, and one of them is running iOS 18.5... Rebooting device won't work.), and we currently have no clue how to troubleshoot this.
Update: The guy running iOS 18.5 told me that the widgets are now discoverable after waiting for minutes. Seems that this is a random issue.
I am experiencing an issue with my watchOS app. My application updates a shared file, accessible by both the main app and the WidgetKit extension, during a WatchConnectivity background task. Following this update, I call reloadAllTimelines().
This functionality worked as expected on watchOS 10, even without Developer Mode enabled. However, after updating my device to watchOS 11.5, this API appears to be broken.
My reasons for believing this API is broken are threefold:
The functionality worked reliably on watchOS 10.
On watchOS 11.5, enabling "WidgetKit Developer Mode" (found under Settings > Developer) resolves the issue, and my complications update correctly.
When I enter watch face edit mode, the snapshot/preview displayed (which utilizes the same underlying logic as the timeline API) shows the correct data. This indicates that the data has been successfully received from the phone, and the widget is indeed reading the updated shared file. Despite this, the actual widget view during its resting phase never updates.
It's worth noting that TimelineReloadPolicy functions as expected, but I cannot rely on this for my use case. My widget requires immediate updates upon receiving new data.
Apple, please investigate this behavior.
Topic:
App & System Services
SubTopic:
Widgets & Live Activities
Tags:
Watch Connectivity
watchOS
Watch Complications
WidgetKit
With the advent of APNs pushs to Widgets, I would like to confirm some things. I understand that we have a budget of updates for it, however is the budget for APNs part of the budget for background updates? In other words, 1 budget for both or 2 separate budgets?
Also, can we make a push to an individual widget, or are we essentially calling .reloadAllTimelines()?
In WatchOS 26 you can now configure Apple Watch Widgets that use AppIntents instead of having a preconfigured option via AppIntentRecommendation.
This is demonstrated in the Weather Details Widget. In that, the Intent has been set up such that the options have icons for each parameter.
How can I update my Intent code to offer this?
struct DataPointsWidgetIntent: AppIntent, WidgetConfigurationIntent {
static var title: LocalizedStringResource = "Data Points Widget Configuration"
static var description = IntentDescription("Configure the individual data point display for Widgets.")
static var isDiscoverable: Bool { return false}
init() {}
func perform() async throws -> some IntentResult {
print("DataPointsWidgetIntent perform")
return .result()
}
@Parameter(title: "Show Individual Data Points", default: true)
var showDataPoints: Bool?
@Parameter(title: "Trend Timescale", default: .week)
var timescale: TimescaleTypeAppEnum?
static var parameterSummary: some ParameterSummary {
Summary("Test Info") {
\.$showDataPoints
\.$timescale
}
}
}
enum TimescaleTypeAppEnum: String, AppEnum {
case week
case fortnight
static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Trend Timescale")
static var caseDisplayRepresentations: [Self: DisplayRepresentation] = [
.week: "Past Week",
.fortnight: "Past Fortnight"
]
}
Topic:
App & System Services
SubTopic:
Widgets & Live Activities
Tags:
WidgetKit
Intents
WeatherKit
App Intents
I have a Health & Fitness widget that runs on iPhone and Apple Watch. As Health data access requires the device to be unlocked, the iPhone widget is already slightly limited in capability because of updates.
With widgets further expanding to places like CarPlay, I know I can use the .disfavouredLocations{} API to try and prevent it being offered there. This is crucial as the widget functionality would be basically non-existent as your device is locked during CarPlay use.
My problem is, on the Mac despite using the .disfavouredLocations{.iPhoneWidgetsOnMac} etc...., the widget can still be added in the "other unsupported section". And yet, in that section the Apple Fitness app widget is no where to be seen. Is there an API I am missing to completely remove a widget from the Mac widget gallery and hopefully CarPlay, Standby etc.... (all places where the device running the widget is usually locked -> No Health data)?
Or does the Apple Fitness app have a private API to block it from these places where its function is not wanted and this isn't available to other apps?
I have an app that uses NSPersistentCloudKitContainer stored in a shared location via App Groups so my widget can fetch data to display. It works. But if you reset your iPhone and restore it from a backup, an error occurs:
The file "Name.sqlite" couldn't be opened. I suspect this happens because the widget is created before the app's data is restored. Restarting the iPhone is the only way to fix it though, opening the app and reloading timelines does not. Anything I can do to fix that to not require turning it off and on again?
I am working on a widget that allows the user to specify a list of items.
Each item is an AppEntity and has an id, a type and a name. In the DisplayRepresentation I have and icon / image for each type. So when I tap on the specified items option a list of user specified items comes up with the option to search, select, deselect items. This works nicely. I sort them suggested entities by type then name so the list is predictable. How would like to be able to have a group / type header for each type of item. However, I don't know how to do that with the AppEntities. Help would be appreciated.
I noticed that HomeKit takes a different approach. They have a list of items at the bottom labeled "Choose Scene Or Accessory". You can move the items up / down in the list, you can delete, and add items. When you tap "Add an item" in the list it goes to a search screen where the items are grouped by the room and have the individual items beneath them. I don't like that you have to select one item at a time but I love having the headings for the rooms. The question here is how did they do that? Is there sample code somewhere that does something similar.
Hello,
I'm trying to create a widget using the WidgetKit framework. In this part, I'm using Intents along with a DynamicOptionsProvider. As shown in the Medium article below, I want to present multiple options when "Edit Widget" is tapped:
https://levelup.gitconnected.com/swiftui-configurable-widget-to-let-our-user-choose-4a54e398f42f
However, in this example, the options are provided statically. What I want to achieve is to display a list of devices based on the selected HomeId after the user selects a Home. I’ve set up the interface accordingly, but when I select a Home, the device list does not update.
How can I make this work? The two options should be dependent on each other.
I need to implement a VPN connection from the ios 17 widget without opening the main application. (I have seen such an implementation in other applications) How can this be implemented?
I've noticed that the when starting live activities via a remote push-to-start notification, the live activity widget consistently succeeds in displaying on the lock screen. However push-to-update token is not always received by the task observing the pushTokenUpdates async-sequence.
Task {
print("listening for pushTokenUpdates")
for await pushToken in activity.pushTokenUpdates {
let token = pushToken.map {String(format: "%02x", $0)}.joined()
print("Push token: \(token)")
}
}
The log will print "listening for pushTokenUpdates" however occasionally the "Push token: ___" line will not be present even when the widget has displayed on screen. This happens even if the "allow" button has been selected on live activities for that app. The inconsistent behavior leads me to believe there is an issue at the ActivityKit level. Would appreciate any feedback in debugging this!
I am seeing a really weird behavior with Live Activities. The Live Activity is always appearing on the simulator. However the Live Activity is only appearing on my physical device when there is no other widget in the widget bundle shown below.
@main
struct HoerspielWidgetsBundle: WidgetBundle {
var body: some Widget {
// Uncomment the line below and the Live Activity will no longer appear
// UpNextWidget()
PlaybackLiveActivity()
}
}
Annotating that var with @WidgetBundle has no effect.
There are no logs indicating an error, the function to request a Live Activity does not throw and the status of the activity is active.
Both the widget and the Live Activity are working fine otherwise. NSSupportsLiveActivities is set to true in the correct Info.plist file. I am not running any beta software and the physical iPhone is on the newest version (iOS 18.5). Using the template when adding a new target in Xcode, I was able to set up a similar app where the Live Activity works as expected.
I am really at a loss here which additional information I should provide or how this issue can be resolved.
Thank you for your help.
I'm working on an iOS app with a Widget. I am able to display the Widget on the iPhone 16 Pro Simulator. It doesn't appear on iPad mini 6th gen., though. Anyway, I want to make sure that it works on an actual device. If I try to add the Widget to the Home Screen, I cannot find it in the search list on iPhone XR and iPad 9th gen. If I set the target to that of the widget, Xcode gives me the following error.
SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget 'some bundle ID' error: …
I hope that's not a sign of trouble. So how do you debug a Widget on an Actual Device? I've read some topics like this one here. Thanks.
I have a SwiftUI app. It fetches records through CoreData. And I want to show some records on a widget. I understand that I need to use AppGroup to share data between an app and its associated widget.
import Foundation
import CoreData
import CloudKit
class DataManager {
static let instance = DataManager()
let container: NSPersistentContainer
let context: NSManagedObjectContext
init() {
container = NSPersistentCloudKitContainer(name: "DataMama")
container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group identifier)!.appendingPathComponent("Trash.sqlite"))]
container.loadPersistentStores(completionHandler: { (description, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
})
context = container.viewContext
context.automaticallyMergesChangesFromParent = true
context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType)
}
func save() {
do {
try container.viewContext.save()
print("Saved successfully")
} catch {
print("Error in saving data: \(error.localizedDescription)")
}
}
}
// ViewModel //
import Foundation
import CoreData
import WidgetKit
class ViewModel: ObservableObject {
let manager = DataManager()
@Published var records: [Little] = []
init() {
fetchRecords()
}
func fetchRecords() {
let request = NSFetchRequest<Little>(entityName: "Little")
do {
records = try manager.context.fetch(request)
records.sort { lhs, rhs in
lhs.trashDate! < rhs.trashDate!
}
} catch {
print("Fetch error for DataManager: \(error.localizedDescription)")
}
WidgetCenter.shared.reloadAllTimelines()
}
}
So I have a view model that fetches data for the app as shown above.
Now, my question is how should my widget get data from CoreData? Should the widget get data from CoreData through DataManager? I have read some questions here and also read some articles around the world. This article ( https://dev.classmethod.jp/articles/widget-coredate-introduction/ ) suggests that you let the Widget struct access CoreData through DataManager. If that's a correct fashion, how should the getTimeline function in the TimelineProvider struct get data? This question also suggests the same. Thank you for your reading my question.
Hello,
I am trying to get the elements from my SwiftData databse in the configuration for my widget.
The SwiftData model is the following one:
@Model
class CountdownEvent {
@Attribute(.unique) var id: UUID
var title: String
var date: Date
@Attribute(.externalStorage) var image: Data
init(id: UUID, title: String, date: Date, image: Data) {
self.id = id
self.title = title
self.date = date
self.image = image
}
}
And, so far, I have tried the following thing:
AppIntent.swift
struct ConfigurationAppIntent: WidgetConfigurationIntent {
static var title: LocalizedStringResource { "Configuration" }
static var description: IntentDescription { "This is an example widget." }
// An example configurable parameter.
@Parameter(title: "Countdown")
var countdown: CountdownEntity?
}
Countdowns.swift, this is the file with the widget view
struct Provider: AppIntentTimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date(), configuration: ConfigurationAppIntent())
}
func snapshot(for configuration: ConfigurationAppIntent, in context: Context) async -> SimpleEntry {
SimpleEntry(date: Date(), configuration: configuration)
}
func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<SimpleEntry> {
var entries: [SimpleEntry] = []
// Generate a timeline consisting of five entries an hour apart, starting from the current date.
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate, configuration: configuration)
entries.append(entry)
}
return Timeline(entries: entries, policy: .atEnd)
}
// func relevances() async -> WidgetRelevances<ConfigurationAppIntent> {
// // Generate a list containing the contexts this widget is relevant in.
// }
}
struct SimpleEntry: TimelineEntry {
let date: Date
let configuration: ConfigurationAppIntent
}
struct CountdownsEntryView : View {
var entry: Provider.Entry
var body: some View {
VStack {
Text("Time:")
Text(entry.date, style: .time)
Text("Title:")
Text(entry.configuration.countdown?.title ?? "Default")
}
}
}
struct Countdowns: Widget {
let kind: String = "Countdowns"
var body: some WidgetConfiguration {
AppIntentConfiguration(kind: kind, intent: ConfigurationAppIntent.self, provider: Provider()) { entry in
CountdownsEntryView(entry: entry)
.containerBackground(.fill.tertiary, for: .widget)
}
}
}
CountdownEntity.swift, the file for the AppEntity and EntityQuery structs
struct CountdownEntity: AppEntity, Identifiable {
var id: UUID
var title: String
var date: Date
var image: Data
var displayRepresentation: DisplayRepresentation {
DisplayRepresentation(title: "\(title)")
}
static var defaultQuery = CountdownQuery()
static var typeDisplayRepresentation: TypeDisplayRepresentation = "Countdown"
init(id: UUID, title: String, date: Date, image: Data) {
self.id = id
self.title = title
self.date = date
self.image = image
}
init(id: UUID, title: String, date: Date) {
self.id = id
self.title = title
self.date = date
self.image = Data()
}
init(countdown: CountdownEvent) {
self.id = countdown.id
self.title = countdown.title
self.date = countdown.date
self.image = countdown.image
}
}
struct CountdownQuery: EntityQuery {
typealias Entity = CountdownEntity
static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Countdown Event")
static var defaultQuery = CountdownQuery()
@Environment(\.modelContext) private var modelContext // Warning here: Stored property '_modelContext' of 'Sendable'-conforming struct 'CountdownQuery' has non-sendable type 'Environment<ModelContext>'; this is an error in the Swift 6 language mode
func entities(for identifiers: [UUID]) async throws -> [CountdownEntity] {
let countdownEvents = getAllEvents(modelContext: modelContext)
return countdownEvents.map { event in
return CountdownEntity(id: event.id, title: event.title, date: event.date, image: event.image)
}
}
func suggestedEntities() async throws -> [CountdownEntity] {
// Return some suggested entities or an empty array
return []
}
}
CountdownsManager.swift, this one just has the function that gets the array of countdowns
func getAllEvents(modelContext: ModelContext) -> [CountdownEvent] {
let descriptor = FetchDescriptor<CountdownEvent>()
do {
let allEvents = try modelContext.fetch(descriptor)
return allEvents
}
catch {
print("Error fetching events: \(error)")
return []
}
}
I have installed it in my phone and when I try to edit the widget, it doesn't show me any of the elements I have created in the app, just a loading dropdown for half a second:
What am I missing here?
Topic:
App & System Services
SubTopic:
Widgets & Live Activities
Tags:
SwiftUI
WidgetKit
App Intents
SwiftData
Is it actually possible to display animation (even a simple one) on Live Activity? But on these cases:
The main app is terminated - of course, I know I can use the main app to keep updating the Live Activity to make simple animations work, but in this case, the main app is killed.
Live Activity data is not updating - I also understand that the Live Activity can perform animations when its data is being update via push notification or other means, but the current case is the data is not being updated.
I’ve tried several ways to achieve this, but nothing seems to work.
Just when I was about to give up, I found this video from Apple’s official channel:
https://www.youtube.com/watch?v=m6WMwSj_EbA
At 4:14 in this video, you can see the text "Locating Driver" with the breathing animation. Could someone please help me understand how to implement that kind of animation in a Live Activity when:
The main app is not running, and
The Live Activity data is not updating?
Is there any way to obtain the ControlWidget installed by user, I use WidgetCenter.shared.getCurrentConfigurations cannot work
Hi, I've seen some apps that can have the widget background truly transparent ( not screenshot, code-level transparent)
How did they do that? Is that allowed to publish in App Store?
I'm currently adding swift widgets to my existing ObjC project and building it for ios-simulator causes a "Swift.h" file not found error. it works without issue for device build. I see the file compiled under DerivedData at and set the Header Search Path and User Header Search Path to: $(CONFIGURATION_TEMP_DIR)/$(PROJECT_NAME).build/DerivedSources but it still doesn't work.
Removing the #import "proj-Swift.h" line fixes the issues, but I need to import it to use WidgetCenter ReloadAllTimelines. I checked that the file is being generated correctly by viewing the autogenerated file and its contents.
Any advice and direction would be a great help. Been stuck on this all week and I can't think of a different solution.
I have an objective-c watch app and have added a swift widget style compilation to it and am having problems. The complication works fine but the name in the iPhone watch app complication picker stubbornly remains as the watchkit app name despite me trying various ways of changing it.
Here are the various CF bundle name and display name values I am using:
phone app values
CFBundleIdentifier - com.Distribution-Systems-Associates.Tennis-Watch-v1
CFBundleName - $(PRODUCT_NAME)
CFBundleDisplayName - Tennis Scorekeeper
watchkit app
CFBundleIdentifier - com.Distribution-Systems-Associates.Tennis-Watch-v1.watchkitapp
CFBundleName - Tennis Scorekeeper
CFBundleDisplayName - Tennis Scorekeeper
WatchKit extension
CFBundleIdentifier - com.Distribution-Systems-Associates.Tennis-Watch-v1.watchkitapp.watchkitextension
CFBundleName - Tennis Scorekeeper
CFBundleDisplayName - Tennis Scorekeeper
__Watchkit complication __
CFBundleIdentifier - com.Distribution-Systems-Associates.Tennis-Watch-v1.watchkitapp.watchkitextension.Tennis-Watch-V1-Complication
Changing the values in the complication doesn't seem to matter. Every other name in both my iPhone and watch apps are as expected.
ChatGPT suggested that I try adding a localized name in the watchkit app but that didn't seem to do much of anything useful. I have run this though Chat quite a bit to see if I could get any accidental insights that way and while it has been interesting, it has also been not terribly helpful.
I didn't post any of the complication code because that seems to be fine. However, I can do that if needed. The complication works as intended (starts the app). The various names everywhere else show up as intended. It's just that this one name refuses to be overridden. Thoughts?
Topic:
App & System Services
SubTopic:
Widgets & Live Activities
Tags:
WatchKit
Swift
Objective-C
WidgetKit