WidgetKit

RSS for tag

Show 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

Control Center Widget icon disappear occasionally
Hi folks, We are trying to develop a widget on iPhone control center. We follow the Apple design guideline to export our resource file using custom icon and the button icon always show on debug build. However, when we deploy to TestFlight, under some scenario, such as app upgrade, we found that the icon image disappear occasionally. Anyone could help? Thank you in advance!
0
0
22
8h
Swipe gestures for widgets
Hey, I am building some widgets and I'm quite surprised that Swipe gestures for widgets is not supported. It means the user must sacrifice home screen real estate to view multiple widgets to receive the same information. Ideally, swiping left / right inside of the widget should give a developer access to present different views. I realize that it means that a user would need to swipe outside of the widget, (or swipe to the beginning/end of the series of views inside of the widget) for the page to swipe, but I'd argue that this is the intuitive behavior of what widget scrollview would or should look like anyway.
1
0
185
5d
Core Data Light Migration Crash When Widget is Installed (Error 134100)
I'm experiencing a crash during a lightweight Core Data migration when a widget that accesses the same database is installed. The migration fails with the following error: CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134100) error: userInfo: CoreData: error: userInfo: error: metadata : { NSPersistenceFrameworkVersion = 1414; NSStoreModelVersionChecksumKey = "dY78fBnnOm7gYtb+QT14GVGuEmVlvFSYrb9lWAOMCTs="; NSStoreModelVersionHashes = { Entity1 = { ... }; Entity2 = { ... }; Entity3 = { ... }; Entity4 = { ... }; Entity5 = { ... }; }; NSStoreModelVersionHashesDigest = "aOalpc6zSzr/VpduXuWLT8MLQFxSY4kHlBo/nuX0TVQ/EZ+MJ8ye76KYeSfmZStM38VkyeyiIPf4XHQTMZiH5g=="; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "" ); NSStoreType = SQLite; NSStoreUUID = "9AAA7AB7-18D4-4DE4-9B54-893D08FA7FC4"; "_NSAutoVacuumLevel" = 2; } The issue occurs only when the widget is installed. If I remove the widget’s access to the Core Data store, the migration completes successfully. The crash happens only once—after the app is restarted, everything works fine. This occurs even though I'm using lightweight migration, which should not require manual intervention. My suspicion is that simultaneous access to the Core Data store by both the main app and the widget during migration might be causing the issue. Has anyone encountered a similar issue? Is there a recommended way to ensure safe migration while still allowing the widget to access Core Data? Any insights or recommendations would be greatly appreciated.
3
0
254
1w
Refresh Widget doesn't work from background push notification.
As stated in other posts like: https://developer.apple.com/forums/thread/734488 https://developer.apple.com/forums/thread/652946?answerId=823555022#823555022 Even though the recommended way from Apple documentation is to use push notifications to reload widgets timelines calling WidgetCenter.shared.reloadAllTimelines(), it is unreliable and I couldn't find a pattern of why it works 10% of times and not the other 90%. While the debugger is connected to the App it always works though. My widget needs to reflect updated information otherwise it becomes useless since it display smart home devices states such as the Apple Home widget does as well.
1
1
167
1w
Widget archival failed due to image being too large
I'm trying to setup a widget to pull an image down from a webserver and I'm running into an error of Widget archival failed due to image being too large [9] - (1024, 1024), totalArea: 1048576 > max[718080.000000]. I've tried two different approaches to resolve this error and both have failed to resolve the image. I've also confirmed that I'm getting the image in the AppIntentTimelineProvider. private func getImageUI(urlString: String) -> UIImage? { guard let url = URL(string: urlString) else { return nil } guard let imageData = try? Data(contentsOf: url) else { return nil } return UIImage(data: imageData)?.resizedForWidget() } Is there another approach I could take on addressing this issue so the image appears on the widget? Simple approach extension UIImage { func resized(toWidth width: CGFloat, isOpaque: Bool = true) -> UIImage? { let canvas = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height))) let format = imageRendererFormat format.opaque = isOpaque return UIGraphicsImageRenderer(size: canvas, format: format).image { _ in draw(in: CGRect(origin: .zero, size: canvas)) } } } extension UIImage { /// Resize the image to strictly fit within WidgetKit’s max allowed pixel area (718,080 pixels) func resizedForWidget(maxArea: CGFloat = 718_080.0, isOpaque: Bool = true) -> UIImage? { let originalWidth = size.width let originalHeight = size.height let originalArea = originalWidth * originalHeight print("🔍 Original Image Size: \(originalWidth)x\(originalHeight) → Total Pixels: \(originalArea)") // ✅ If the image is already within the limit, return as is if originalArea <= maxArea { print("✅ Image is already within the allowed area.") return self } // 🔄 Calculate the exact scale factor to fit within maxArea let scaleFactor = sqrt(maxArea / originalArea) let newWidth = floor(originalWidth * scaleFactor) // Use `floor` to ensure area is always within limits let newHeight = floor(originalHeight * scaleFactor) let newSize = CGSize(width: newWidth, height: newHeight) print("🛠 Resizing Image: \(originalWidth)x\(originalHeight) → \(newWidth)x\(newHeight)") // ✅ Force bitmap rendering to ensure the resized image is properly stored let format = UIGraphicsImageRendererFormat() format.opaque = isOpaque format.scale = 1 // Ensures we are not letting UIKit auto-scale it back up let renderer = UIGraphicsImageRenderer(size: newSize, format: format) let resizedImage = renderer.image { _ in self.draw(in: CGRect(origin: .zero, size: newSize)) } print("✅ Final Resized Image Size: \(resizedImage.size), Total Pixels: \(resizedImage.size.width * resizedImage.size.height)") return resizedImage } } These are logs from a failed image render if that helps 🔍 Original Image Size: 720.0x1280.0 → Total Pixels: 921600.0 🛠 Resizing Image: 720.0x1280.0 → 635.0x1129.0 ✅ Final Resized Image Size: (635.0, 1129.0), Total Pixels: 716915.0
1
0
216
2w
Widgets not showing up in MacOS widget gallery
I have a multiplatform app that I've been working on that targets iphones, ipad, and macos. I also have a widgetextension that targets all three devices. On iphones and ipads, the widgets show up in the widget gallery with no problems. But on the mac, the widget center does show my app, but its widgets are "from iPhone" meaning that if my app was not install on an iphone, they just won't show up on the mac at all. I have not idea of what I'm doing wrong or how to fix it. Do I need to create a widget extension for the mac seperately?
2
0
203
5d
Can the current implementation of lock screen widgets match what behaviors of the deprecated Today Extensions?
In the past it was possible to use the Today Extensions to do some background processing without having the unlock the phone. This was extremely useful for application, but now with the current WidgetKit we face the problem of sometimes having to enter the lock screen code if face Id fails, or is not available. With the Today Extension, we were able to initiate a location request and send an HTTP request. Is there any way to get a similar request chain across on the latest OS? Maybe there is something out of the box that we are not thinking of. Our application is highly time sensitive and in the field the lock screen delay can be a big problem and put a users safety at risk, so this is why I ask.
1
0
186
4w
WidgetKit Simulator with Intent Configurations
Xcode 16.2 are unavailable to develop widget with dynamic options, no matter SiriIntent or AppIntent that I try to use. I have try to start a complete new project, then add widget with app intent checkbox check, with zero code changed then i press command run and WidgetKit Simulator present CHSErrorDomain error 1103 always, if i try to add widget directly from desktop, dynamic options are available to select but widgets doesn't seem like load successfully, it is stuck same in the WidgetKit Simulator. I also try to start a new project in my other MacBook but no luck, this error are presenting all the time, I'm totally stuck here, does anybody having this issue?
2
0
329
3w
Custom Intent ParameterSummary based on Widget Kind/ID
I'm trying to create two widgets, widget A and B. Currently A and B are very similar so they share the same Intent and Intent Timeline Provider. I use the Intent Configuration interface to set a parameter, in this example lets say its the background tint. On one of the widgets, widget A, I want to also set another String enum parameter (for a timescale), but I don't want this option to be there for widget B as it's not relevant. I'm aware of some of the options for configuring the ParameterSummary, but none that let me pass in or inject the "kind" string (or widget ID) of the widget that's being modified. I'll try to provide some code for examples. My Widget Definition (targeting >= iOS 17) struct WidgetA: Widget { // I'd like to access this parameter within the intent let kind: String = "WidgetA" var body: some WidgetConfiguration { AppIntentConfiguration(kind: kind, intent: WidgetIntent.self, provider: IntentTimelineProvider()) { entry in WidgetView(data: entry) } .configurationDisplayName("Widget A") .description("A widget.") .supportedFamilies([.systemMedium, .systemLarge]) } } struct WidgetB: Widget { let kind: String = "WidgetB" var body: some WidgetConfiguration { AppIntentConfiguration(kind: kind, intent: WidgetIntent.self, provider: IntentTimelineProvider()) { entry in WidgetView(data: entry) } .configurationDisplayName("Widget B") .description("B widget.") .supportedFamilies([.systemMedium, .systemLarge]) } } struct IntentTimelineProvider: AppIntentTimelineProvider { typealias Entry = WidgetIntentTimelineEntry typealias Intent = WidgetIntent ........ } struct WidgetIntent: AppIntent, WidgetConfigurationIntent { // This intent allows configuration of the widget background // This intent also allows for the widget to display interactive buttons for changing the Trend Type static var title: LocalizedStringResource = "Widget Configuration" static var description = IntentDescription("Description.") static var isDiscoverable: Bool { return false} init() {} init(trend:String) { self.trend = trend } // Used for implementing interactive Widget func perform() async throws -> some IntentResult { print("WidgetIntent perform \(trend)") #if os(iOS) WidgetState.setState(type: trend) #endif return .result() } @Parameter(title: "Trend Type", default: "Trend") var trend:String // I only want to show this parameter for Widget A and not Widget B @Parameter(title: "Trend Timescale", default: .week) var timescale: TimescaleTypeAppEnum? @Parameter(title: "Background Tint", default: BackgroundTintTypeAppEnum.none) var backgroundTint: BackgroundTintTypeAppEnum? static var parameterSummary: some ParameterSummary { // Summary("Test Info") { // \.$timescale // \.$backgroundTint // } // An example of a configurable widget parameter summary, but not based of kind/ID string When(\.$backgroundTint, .equalTo, BackgroundTintTypeAppEnum.none) { Summary("Test Info") { \.$timescale \.$backgroundTint } } otherwise : { Summary("Test Info") { \.$backgroundTint } } } } 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" ] } enum BackgroundTintTypeAppEnum: String, AppEnum { case blue case none static var typeDisplayRepresentation = TypeDisplayRepresentation(name: "Background Tint") static var caseDisplayRepresentations: [Self: DisplayRepresentation] = [ .none: "None (Default)", .blue: "Blue" ] } I know I could achieve what I'm after by having a separate Intent and separate IntentTimelineProvider for each widget. But this all seems unnessecary for just a simple optional parameter based on what widget its configuring.... unless I'm missing the point about Intents, Widgets or something! I've done a fair bit of other searching but can't find an answer to this overall scenario. Many thanks for any help.
1
0
234
Jan ’25
iOS Widget can't connect to the host app and shows Skeleton.
Some of our users keep reporting that occasionally some widgets (which initially were working perfectly) are now broken and show only skeletons. Note that the app has multiple widgets, and this happens only to some of them (that is when some widgets get broken, some other widgets are still working normally). While developing the app, I came across this symptom as well, and when I read the device console, I found the following errors in the console (which the system was repeatedly reporting to the console): Unable to get connection interface: Error Domain=LNConnectionErrorDomain Code=1100 "Unable to locate com.example.app.MyAppntents for the com.apple.intents-service extension point" UserInfo={NSLocalizedDescription=Unable to locate com.example.app.MyAppIntents for the com.apple.intents-service extension point} The affected widgets use the 'UserDefaults with groups' to read the data that is stored by the host app. And I think that sometimes the widget fails (or even crashes) while reading the data from the UserDefaults and it ends up showing the skeleton. The only remedy I found was Uninstall the app Reboot the device Install the app again. After this, the widget starts to work again.. So, what can be the reason behind this? Is this an iOS bug or what and how to fight it?
2
0
218
Jan ’25
Lockscreen widget error
I am trying to create a lockscreen widget that is a deepink to a page in my app, but I am getting an error once building the widget itself (building the app works). Currently, the app is on my phone as well as the widget on my lockscreen, but the widget only goes to either my homepage or the page I was last on if the app wasn't fully closed. I've been stuck on this feature and can't get any progress on getting it to work properly... The error: SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget '.widget' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace)., BSErrorCodeDescription=RequestDenied, NSUnderlyingError=0x7fea68510 {Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=3 "Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)" UserInfo={NSLocalizedDescription=Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)}}, FBSOpenApplicationRequestID=0x8b49, NSLocalizedDescription=The request to open "com.apple.springboard" failed.}." UserInfo={NSLocalizedDescription=Failed to show Widget '.widget' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace)., BSErrorCodeDescription=RequestDenied, NSUnderlyingError=0x7fea68510 {Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=3 "Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)" UserInfo={NSLocalizedDescription=Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)}}, FBSOpenApplicationRequestID=0x8b49, NSLocalizedDescription=The request to open "com.apple.springboard" failed.}., NSUnderlyingError=0x7fea68540 {Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace)., BSErrorCodeDescription=RequestDenied, NSUnderlyingError=0x7fea68510 {Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=3 "Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)" UserInfo={NSLocalizedDescription=Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)}}, FBSOpenApplicationRequestID=0x8b49, NSLocalizedDescription=The request to open "com.apple.springboard" failed.}}} Domain: DTXMessage Code: 1 User Info: { DVTErrorCreationDateKey = "2025-01-14 01:35:08 +0000"; } SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget '.widget' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace)., BSErrorCodeDescription=RequestDenied, NSUnderlyingError=0x7fea68510 {Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=3 "Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)" UserInfo={NSLocalizedDescription=Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)}}, FBSOpenApplicationRequestID=0x8b49, NSLocalizedDescription=The request to open "com.apple.springboard" failed.}." UserInfo={NSLocalizedDescription=Failed to show Widget '.widget' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace)., BSErrorCodeDescription=RequestDenied, NSUnderlyingError=0x7fea68510 {Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=3 "Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)" UserInfo={NSLocalizedDescription=Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)}}, FBSOpenApplicationRequestID=0x8b49, NSLocalizedDescription=The request to open "com.apple.springboard" failed.}., NSUnderlyingError=0x7fea68540 {Error Domain=FBSOpenApplicationServiceErrorDomain Code=1 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedFailureReason=The request was denied by service delegate (SBMainWorkspace)., BSErrorCodeDescription=RequestDenied, NSUnderlyingError=0x7fea68510 {Error Domain=SBAvocadoDebuggingControllerErrorDomain Code=3 "Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)" UserInfo={NSLocalizedDescription=Request widget family (systemMedium) is not supported by this widget kind (TransactionLockScreenWidget)}}, FBSOpenApplicationRequestID=0x8b49, NSLocalizedDescription=The request to open "com.apple.springboard" failed.}}} Domain: DTXMessage Code: 1 System Information macOS Version 15.2 (Build 24C101) Xcode 16.2 (23507) (Build 16C5032a) Timestamp: 2025-01-13T19:35:08-06:00
1
0
169
Jan ’25
Use of WidgetConfigurationIntent WidgetKit configurable parameter unable to internationalization of the title?
struct DeployAndWithdrawDefensesAppIntent: WidgetConfigurationIntent { // An example configurable parameter. @Parameter(title:LocalizedStringResource("ax_alarm_device_name")) } In the process of using iOS widgetKit development team a, configuration item title need language internationalization (@ Parameter (title: LocalizedStringResource (" ax_alarm_device_name "))), but found no effect. I first changed the language of the system on the iphone and found that the widget worked. However, just changing the language of the app did not take effect. Is there any way to just change the app language and make the widgets change? Thank you very much!
1
0
520
Jan ’25
Can't Widgetkit use lottie to implement the isOn state of toggle?
I introduced lottie to toggle in my widget to show a transition animation, but found that the.json file wouldn't load. The loading_hc.json file is validated and exists in the widget target. Ask for help, thank you! struct LottieView: UIViewRepresentable { let animationName: String func makeUIView(context: Context) -> LOTAnimationView { let lotAnimationView = LOTAnimationView(name: animationName, bundle: .main) lotAnimationView.contentMode = .scaleAspectFit lotAnimationView.play() return lotAnimationView } func updateUIView(_ uiView: LOTAnimationView, context: Context) { } func makeCoordinator() -> Coordinator { Coordinator() } } struct ControlToggleDisarmingStyle: ToggleStyle { func makeBody(configuration: Configuration) -> some View { if configuration.isOn { LottieView(animationName: "loading_hc.json").foregroundColor(.clear).frame(width: 24,height: 24) } else { Image("icon_disarm", bundle: Bundle.main).foregroundColor(.clear) } } }
2
0
301
Jan ’25
Using isActivityFullscreen to build applications in xcode 16 will crash in ios 17
My widget uses the @Environment(.isActivityFullscreen) variable. When running on ios 17, it will crash and report an error: dyld[55031]: Symbol not found: _$s7SwiftUI17EnvironmentValuesV9WidgetKitE20isActivityFullscreenSbvg Expected in: /Library/Developer/CoreSimulator/Volumes/iOS_21E213/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 17.4.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/WidgetKit.framework/WidgetKit
0
0
203
Jan ’25
Triggering a Live Activity from a Widget-Based App Intent
Hello everyone, I have an app leveraging SwiftData, App Intents, Interactive Widgets, and a Control Center Widget. I recently added Live Activity support, and I’m using an App Intent to trigger the activity whenever the model changes. When the App Intent is called from within the app, the Live Activity is created successfully and appears on both the Lock Screen and in the Dynamic Island. However, if the same App Intent is invoked from a widget, the model is updated as expected, but no Live Activity is started. Here’s the relevant code snippet where I call the Live Activity: ` await LiveActivityManager.shared.newSessionActivity(session: session) And here’s how my attribute is defined: struct ContentState: Codable, Hashable { var session: Session } } Is there any known limitation or workaround for triggering a Live Activity when the App Intent is initiated from a widget? Any guidance or best practices would be greatly appreciated. Thank you! David
1
0
347
Jan ’25
get location in app intent for interactive widgets
I have an app intent for interactive widgets. when I touch the toggle, the app intent perform to request location. func perform() async throws -> some IntentResult { var mark: LocationService.Placemark? do { mark = try await AsyncLocationServive.shared.requestLocation() print("[Widget] ConnectHandleIntent: \(mark)") } catch { WidgetHandler.shared.error = .locationUnauthorized print("[Widget] ConnectHandleIntent: \(WidgetHandler.shared.error!)") } return .result() } @available(iOSApplicationExtension 13.0, *) @available(iOS 13.0, *) final class AsyncLocationServive: NSObject, CLLocationManagerDelegate { static let shared = AsyncLocationServive() private let manager: CLLocationManager private let locationSubject: PassthroughSubject<Result<LocationService.Placemark, LocationService.Error>, Never> = .init() lazy var geocoder: CLGeocoder = { let geocoder = CLGeocoder() return geocoder }() @available(iOSApplicationExtension 14.0, *) @available(iOS 14.0, *) var isAuthorizedForWidgetUpdates: Bool { manager.isAuthorizedForWidgetUpdates } override init() { manager = CLLocationManager() super.init() manager.delegate = self } func requestLocation() async throws -> LocationService.Placemark { let result: Result<LocationService.Placemark, LocationService.Error> = try await withUnsafeThrowingContinuation { continuation in var cancellable: AnyCancellable? var didReceiveValue = false cancellable = locationSubject.sink( receiveCompletion: { _ in if !didReceiveValue { // subject completed without a value… continuation.resume(throwing: LocationService.Error.emptyLocations) } }, receiveValue: { value in // Make sure we only send a value once! guard !didReceiveValue else { return } didReceiveValue = true // Cancel current sink cancellable?.cancel() // We either got a location or an error continuation.resume(returning: value) } ) // Now that we monitor locationSubject, ask for the location DispatchQueue.global().async { self.manager.requestLocation() } } switch result { case .success(let location): // We got the location! return location case .failure(let failure): // We got an error :( throw failure } } // MARK: CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { defer { manager.stopUpdatingLocation() } guard let location = locations.first else { locationSubject.send(.failure(.emptyLocations)) return } debugPrint("[Location] location: \(location.coordinate)") manager.stopUpdatingLocation() if geocoder.isGeocoding { geocoder.cancelGeocode() } geocoder.reverseGeocodeLocation(location) { [weak self] marks, error in guard let mark = marks?.last else { self?.locationSubject.send(.failure(.emptyMarks)) return } debugPrint("[Location] mark: \(mark.description)") self?.locationSubject.send(.success(mark)) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationSubject.send(.failure(.errorMsg(error.localizedDescription))) } } I found it had not any response when the app intent performed. And there is a location logo tips in the top left corner of phone screen.
2
0
325
Jan ’25