WidgetKit

RSS for tag

Show relevant, glanceable content from your app on the iOS Home screen, iOS Lock screen, in macOS Notification Center, and as complications on Apple Watch.

WidgetKit Documentation

Posts under WidgetKit tag

255 Posts
Sort by:
Post not yet marked as solved
0 Replies
77 Views
How can you expose only Dynamic Island? You can't expose Liver Activity Because I'm trying to change the text in real time in the background, but it's not possible in the app, so I just want to expose the dynamic island So I only want to expose compact and minimal presentations
Posted
by dasol.
Last updated
.
Post not yet marked as solved
0 Replies
91 Views
We are running into a major issue with building an iOS Widget. iOS Widgets are basically large informational app icons you can pin to your iPhone home screen (What is a widget?). iOS widgets were introduced in iOS 14. We’ve finished building our iOS widget. However, when half of our users attempt to search for our widget after downloading our app, our widget is not showing up in the widget search results. For the other half, it works fine. This seems to be somewhat of a bug from Apple, as it is affects other widget apps (Apple Thread, the problem exists for large widget apps also). It seems like we are having this issue far more, percentage-wise, than other widget apps. I’ve searched through nearly every resource online (StackOverflow, etc.), which is why I’m posting a question now. Things like deleting the app and reinstalling, restarting the phone, etc. have not been a fix either for these problematic users. It doesn't seem to be tied to any iOS version (14, 15, etc.). As I have iOS 15, and it works fine. But, some users with iOS 15 are getting the bug. Has anyone ran into this issue where a widget is not searchable? How did you fix it? Any resources are appreciated as I am at a major blocker right now. Since my app is primarily based on iOS widgets, this makes it basically unusable for certain users.
Posted
by tlyf0824.
Last updated
.
Post marked as solved
11 Replies
1.5k Views
I understand that complications in WidgetKit and watchOS 9 are different to the old ClockKit way, and I'm trying to populate the getSnapshot, getPlaceholder and getTimeline functions appropriately for the new method. I'm using dynamic intents, and I've got that working and providing a set of items I want the user to choose from, but at the various stages of selecting and adding a complication to the watch face, nothing I do seems to work properly on a device, and sometimes in the Simulator. On the Simulator: 1: The previews all use the same data, but getSnapshot() is supposed to return the data specific to that event from the configuration, i.e. if let theId = configuration.event?.identifier. "Christmas" is correct, but "Gallery Opening" is using Christmas's data. Are you only supposed to show ONE particular bit of data, like some dummy preview data or something? I can do that, but the complication picker then just looks really boring, with just the text below being different. I note that Apple's weather complications show different data. How did they do that? 2: You can see that once I pick an event it's displayed correctly in the Watch face edit screen: The "72d" circular complication is the "New York" event, and the rectangular one is correctly using the data for the "London Party!". 3: Once I've selected the events I want to use in those complications the edit screen shows them as totally blank, not even a placeholder. Which method gives us that preview? 4: Once I confirm the edits and return to the Watch face, the complications appear correctly: Note: This is all from the Simulator (apart from the image of Apple's Weather complications). This stuff barely works on a device. Half the time the complications are all placeholders, and half the time they're using the wrong data! If it works in the Simulator, it should work on the phone, or there is no point in giving us the Simulator if the results are different. So basically: Q1. How do I use different data in the complications picker? Q2. How do you get the previews to show when you're in edit mode? Q3. Does anyone know how to get print() statements to work when I'm running the Complications scheme? I could answer all these questions myself if I could output some debug info to the console, but all I see is the output from the Watch App target...
Posted
by darkpaw.
Last updated
.
Post not yet marked as solved
11 Replies
6.4k Views
I had to create a separate thread for the problem I'm facing with WidgetKit. Environment: Xcode 12.0.1 iOS 14.0 App targeting iOS 10 Widget targeting iOS 14 Intents Extension targeting iOS 10 • I have created Intents Extension. • Created Intents Definition file in Widget target, added it to all the three targets (app, widget, intents extension).  • Declared conformance to the intent handling protocol in IntentHandler (Intents Extension). • Set up Intent Timeline Provider in Widget target.  • Added Siri to the app capabilities. If I go to Edit widget -> tap on a dynamic option it says: No options were provided for this parameter. Intents Extension provides data, but I'm not sure how iOS wires the Intents Extension and widget. From what I see I'm sure that my code inside IntentsHandler.swift is never called.
Posted
by Jauzee.
Last updated
.
Post not yet marked as solved
2 Replies
738 Views
I'm trying to migrate from Complication with CLKComplication to WidgetKit. I have implemented the required methods in https://developer.apple.com/documentation/widgetkit/converting-a-clockkit-app, but the migration is not working. There is no evidence that the method for migration is also called. It was the same with Xcode 14.0.1 and Xcode 14.1RC. class ComplicationController: NSObject, CLKComplicationDataSource, CLKComplicationWidgetMigrator { ...     @available(watchOS 9.0, *)     var widgetMigrator: CLKComplicationWidgetMigrator {         return self     }     @available(watchOS 9.0, *)     func widgetConfiguration(from complicationDescriptor: CLKComplicationDescriptor) async -> CLKComplicationWidgetMigrationConfiguration? {         return CLKComplicationStaticWidgetMigrationConfiguration(kind: "MyWidget", extensionBundleIdentifier: "com.example.myapp.mywatchkitapp.mywidget")     } } What's wrong? Has anyone been able to migrate?
Posted Last updated
.
Post marked as solved
3 Replies
400 Views
I can't fetch the weather using the WeatherKit framework inside a Widget Extension. Here's a project I created just for this example. This widget shows the humidity of a sample location. Here's the code: import WidgetKit import SwiftUI import WeatherKit import CoreLocation struct Provider: TimelineProvider { func placeholder(in context: Context) -> SimpleEntry { SimpleEntry(date: Date(), humidity: 9.99) // placeholder humidity } func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) { let entry = SimpleEntry(date: Date(), humidity: 9.99) // placeholder humidity completion(entry) } func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) { Task { let nextUpdate = Date().addingTimeInterval(3600) // 1 hour in seconds let sampleLocation = CLLocation(latitude: 51.5072, longitude: 0.1276) // sample location (London) let weather = try await WeatherService.shared.weather(for: sampleLocation) let entry = SimpleEntry(date: .now, humidity: weather.currentWeather.humidity) let timeline = Timeline(entries: [entry], policy: .after(nextUpdate)) completion(timeline) } } } struct SimpleEntry: TimelineEntry { let date: Date let humidity: Double } struct WidgetWeatherTestWidgetEntryView : View { var entry: Provider.Entry var body: some View { Text("\(entry.humidity)") } } struct WidgetWeatherTestWidget: Widget { let kind: String = "WidgetWeatherTest" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: Provider()) { entry in WidgetWeatherTestWidgetEntryView(entry: entry) } .configurationDisplayName("Widget Weather Test") .description("Testing weatherkit in a Widget") .supportedFamilies([.systemMedium]) } } It works fine in the simulator: But it doesn't work in a real device. As soon as I call WeatherService's weather(for: CLLocation) async throws -> Weather the widget get's "blocked": I've tried moving the try await WeatherService.shared.weather(for: sampleLocation) to different places, but nothing worked. As soon as I comment out this line (and create an entry with a placeholder humidity) everything works. I added the WeatherKit capability in the main app target and in the WidgetExtension target. I also added the WeatherKit "Capability" and "App Service" in the "Certificates, Identifiers & Profiles" of the Apple Developer website. The WeatherKit framework works fine in other parts of the main app. I haven't tried using the WeatherKit REST API, yet. Any ideas what could be happening?
Posted
by Flict.
Last updated
.
Post not yet marked as solved
6 Replies
1.7k Views
I am trying to add widget extensions to my existing watch app which is in turn attached to an iOS app. I am getting this error: Please try again later. Unable To Install “nextBellWatch” Please try again later. WatchKit 2.0 app's bundle ID com.seanmccomas.nextBellSingleView.watchkitapp is not prefixed by the parent app's bundle ID followed by a '.'; expected prefix . Here are my bundle IDs: iOS App: com.seanmccomas.nextBellSingleView iOS widget extension: com.seanmccomas.nextBellSingleView.NextBellWidget watch app: com.seanmccomas.nextBellSingleView.watchkitapp watch widget extension: com.seanmccomas.nextBellSingleView.watchkitapp.widget What am I missing? I feel like I have done everything right.
Posted Last updated
.
Post not yet marked as solved
5 Replies
1.4k Views
Hello, I am building a SwiftUI app that implements a widget. The user can add different configurations inside the app and then he can choose one by editing the widget. Everything works correctly for almost all of the possible configurations, the widget getTimeline function gets called, all the parameters are passed to the entry successfully and the widget displays. However the problem appears for some specific configurations, as soon as the user sets the widget configuration by tapping on it, it gets stuck on the loading animation and shows no content. The only thing that makes these configurations different is the view body. These configurations show more elements, such as Images and Text. I tried removing few elements and the widgets started working. To make an example there's a widget configuration that is made by a ZStack with a VStack inside, containing 3 HStacks which again contain 1 Text and 1 Image each. Removing 2 HStacks and keeping only one makes the widget load. Is there something I am missing? Is there some limit to widgets view elements? I even checked the ram usage and it appears to be around 10mb for each widget. Also I noticed that rebooting the device makes the widget load. Thanks in advance for any help.
Posted Last updated
.
Post not yet marked as solved
1 Replies
802 Views
Though I moved most of the code to a framework to be able to unit test, still the timelineProvider code is not able to unit test, mainly because Context can't even be created. Please let me know the best practice for unit testing widgets code. Thanks!
Posted
by radhap.
Last updated
.
Post not yet marked as solved
2 Replies
588 Views
I was working on widget and saw that on Xcode 13.4 after initializing the widget from target, If I make even minor changes in the EntryView body, it crashes when I run it 2-3 times and then only after mac restart, it works again. for each change, I have to restart Mac I have uploaded a sample project with the issue in the stackoverflow basically, created a new project, added Widget Extension Target. can be reproduced by anyone in 10 mins. Steps to reproduce: run the external widget once in simulator in Struct ExternalWidgetEntryView, remove the HStack and one Text OR change from add another text OR change it to VStack. run it again on the same simulator. the app widget crashes on running and I see this [Image attached in the stackoverflow question] https://stackoverflow.com/questions/72790887/static-configuration-widget-crash-on-xcode-13-4-1-springboard-crash   Not sure if there is any XCode config I can do to solve this.
Posted
by subodhsah.
Last updated
.
Post not yet marked as solved
2 Replies
526 Views
I'm trying to use a custom font in my Live Activitiy view. To do so, I copy the TTF file into the bundle in the Copy Bundle Resources build phase and add a corresponding entry in the UIAppFonts dictionary in my widget extension's Info.plist. I specify a custom font for one of my Text views as follows: Font.custom("RobotoMono-Bold", size: 12), where the string is equal to the TTF file name. This approach works fine in SwiftUI previews and the custom font renders as expected, but when I try requesting an Activity from my app, the Live Activity never starts. The Activity.request(attributes:contentState:) completes successfully but neither the Dynamic Island, nor the Lock Screen or Notification Center show the activity. Inspecting the simulator's logs in Console.app, I see a suspicious error: Task [2] [my.app.bundle.WidgetExtension:Attributes type: MyActivityAttributes:35E934FB-D3BF-4929-B7A0-90E0886E1F1E] Reload failed; 1 retries remaining: com.apple.chrono.activites.content (1) ChronoKit.PlatterFetchingError(targetIdentifer: [my.app.bundle.WidgetExtension:Attributes type: MyActivityAttributes:35E934FB-D3BF-4929-B7A0-90E0886E1F1E], contentErrors: [ChronoKit.PlatterContentError(code: Returned timeline could not be accepted, targetIdentifer: [my.app.bundle.WidgetExtension:Attributes type: MyActivityAttributes:35E934FB-D3BF-4929-B7A0-90E0886E1F1E], contentIdentifer: [w:fix-373.00-h:dyn-64.00-160.00-cr:12.0], destinationURL: nil, underlyingError: Optional(ChronoKit.RequestCompletionOperation.Error.archiveTooLarge(fileSize: 2591912.0 B)))]) Note the archiveTooLarge(fileSize:) error type at the end that indicates some archive's size to be about 2.5 MB. I'm not sure which archive this error is referring to and how I can influence it. My WidgetExtension.appex bundle is 704 KB in size before adding the custom font and 857 KB afterwards. The TTF file itself is 109 KB in size. Is using a custom font in a Live Activity this way supposed to work, am I just doing something wrong, or am I running into a limitation of the system here?
Posted
by iMoritz.
Last updated
.
Post not yet marked as solved
2 Replies
400 Views
I want to add a widget to my app that will display the # of pickups the user has for the day. I have the DeviceActivityReport working in the main app but can't get it to display in the widget since it is not a supported view for widgets. Is there any workaround for getting this view to the widget? I tried converting the DeviceActivityReport view to a UI image thinking maybe that would be a way to use a widget approved view type but ImageRenderer seems to fail to render an image for the view (which is just a Text view). To summarize my questions: Is it possible to display a DeviceActivityReport in a widget? If so, what is the best practice? Is converting the DeviceActivityReport view into an image and displaying that in a widget an option? Here's my attempt to convert the DeviceActivityReport view into a UIImage: import SwiftUI import _DeviceActivity_SwiftUI struct PickupsDeviceActivityReport: View {     @State private var context: DeviceActivityReport.Context = .totalActivity     @State private var renderedImage = Image(systemName: "exclamationmark.triangle")     @Environment(\.displayScale) var displayScale     var body: some View {         renderedImage             .onAppear { render() }             .onChange(of: context) {                 _ in render()             }     }     @MainActor func render() {         let renderer = ImageRenderer(content: DeviceActivityReport(context))         renderer.scale = displayScale         if let uiImage = renderer.uiImage {             renderedImage = Image(uiImage: uiImage)         }     } } Help is appreciated. Thank you.
Posted Last updated
.
Post not yet marked as solved
1 Replies
360 Views
Hello! I have a problem with apple watch widgets. My widgets are masked when apple watch is locked. The widget just displays a simple image and text and is only used to launch my app. When I wrote ".privacySensitive(false)" in the part I wanted to display, it was displayed even when the device was locked. But the "accessoryInline" type widget is not displayed. Widgets from Apple official apps and some popular apps (such as Spotify) are displayed even if they are of type "accessoryInline". Please let me know if you know how to fix it.
Posted
by potato88.
Last updated
.
Post not yet marked as solved
0 Replies
364 Views
Hello! I made a lock screen widget that is much-needed, However, it does not appear on the lock screen of the actual iOS. I tried changing the Extension, but that does not appear to work. Here is my code: import WidgetKit import SwiftUI struct Provider: TimelineProvider {     func placeholder(in context: Context) -> SecondsEntry {         SecondsEntry(date: Date())     }     func getSnapshot(in context: Context, completion: @escaping (SecondsEntry) -> ()) {         let entry = SecondsEntry(date: Date())         completion(entry)     }     func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {         var entries: [SecondsEntry] = []         // Generate a timeline consisting of five entries an hour apart, starting from the current date.         let currentDate = Date()         for secondOffset in 0 ..< 60 {             let entryDate = Calendar.current.date(byAdding: .second, value: secondOffset, to: currentDate)!             let entry = SecondsEntry(date: entryDate)             entries.append(entry)         }         let timeline = Timeline(entries: entries, policy: .atEnd)         completion(timeline)     } } struct SecondsEntry: TimelineEntry {     let date: Date } struct SecondsEntryView : View {     @Environment(\.widgetFamily) var widgetFamily     var entry: Provider.Entry     var body: some View {         switch widgetFamily {         case .accessoryCircular:             Gauge(value: 1) {                 Text(entry.date.secondDisplayFormat)                     .font(.largeTitle)             }             .gaugeStyle(.accessoryCircularCapacity)         case .accessoryRectangular:             HStack {                 Text(entry.date.secondDisplayFormat)                     .font(.title)                 Text("Seconds")                     .font(.headline)             }                          case .accessoryInline:             Text("● " + entry.date.secondDisplayFormat +  " Seconds")                 .font(.largeTitle)         default:             Text("Error loading...")         }     } } struct Seconds: Widget {     let kind: String = "Seconds"     var body: some WidgetConfiguration {         StaticConfiguration(kind: kind, provider: Provider()) { entry in             SecondsEntryView(entry: entry)         }         .configurationDisplayName("Seconds")         .description("You will be able to track seconds, directly on your lock screen")         .supportedFamilies([.accessoryInline, .accessoryCircular, .accessoryRectangular])     } } struct Seconds_Previews: PreviewProvider {     static var previews: some View {         SecondsEntryView(entry: SecondsEntry(date: Date()))             .previewContext(WidgetPreviewContext(family: .accessoryInline))             .previewDisplayName("Inline")         SecondsEntryView(entry: SecondsEntry(date: Date()))             .previewContext(WidgetPreviewContext(family: .accessoryCircular))             .previewDisplayName("Circular")         SecondsEntryView(entry: SecondsEntry(date: Date()))             .previewContext(WidgetPreviewContext(family: .accessoryRectangular))             .previewDisplayName("Rectangular")     } } extension Date {     var secondDisplayFormat: String {         self.formatted(.dateTime.second())     } }
Posted
by LocalWE.
Last updated
.
Post not yet marked as solved
0 Replies
418 Views
For almost a year now, it has been impossible to switch to a new tool, due to the lack of functionality of the old version. I mean the lack of the ability to create a normal angular layout (when there is a view progress, and an inscription is curved above it). Maybe I'm doing something wrong, but I didn't manage to create something similar to a standard complication. Please provide an example of how standard complications of this type were implemented and how to make it use SwiftUI.
Posted
by Idttm.
Last updated
.
Post not yet marked as solved
0 Replies
234 Views
I added new model version and select it like default one. Then I added new attribute to existing entity in new model version. To test migration I installed previous version of app and add filled with all data in app. Then I install new changes and it work on simulator. If I move that build to TestFlight and test via real device then I get this error: Fatal error: ###persistentContainer: Failed to load persistent stores:Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={sourceURL=file:///private/var/mobile/Containers/Shared/AppGroup/DBB80C75-1B07-4318-8BA3-3F4FFC14FBD7/AppName.sqlite, reason=Cannot migrate store in-place: near "null": syntax error, destinationURL=file:///private/var/mobile/Containers/Shared/AppGroup/DBB80C75-1B07-4318-8BA3-3F4FFC14FBD7/AppName.sqlite, NSUnderlyingError=0x281958180 {Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={reason=near "null": syntax error, NSSQLiteErrorDomain=1, NSUnderlyingException=near "null": syntax error}}} I need to use CoreData for Widget's target as well. Code is here : final class CoreDataStack {     static let shared = CoreDataStack()     var context: NSManagedObjectContext { persistentContainer.viewContext }     var container: NSPersistentContainer { persistentContainer }     private let containerName = "AppName"     private var persistentContainer: NSPersistentContainer!     // MARK: - Setup     func setup() {         guard let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "app_group")?.appendingPathComponent(containerName + ".sqlite") else {             fatalError("Error finding Model from File Manager")         }         let container = NSPersistentContainer(name: containerName)         let description = NSPersistentStoreDescription(url: storeURL)         description.type = NSSQLiteStoreType         description.shouldMigrateStoreAutomatically = true         description.shouldInferMappingModelAutomatically = true         container.persistentStoreDescriptions = [description]         container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy         container.viewContext.transactionAuthor = appTransactionAuthorName         container.viewContext.automaticallyMergesChangesFromParent = true         container.loadPersistentStores(completionHandler: { (_, error) in             if let error = error as NSError? {                 let crashlitycService: CrashlitycUseCase = CrashlitycService()                 crashlitycService.record(error: .errorForAnalytic(error), file: #file, function: #function, line: #line)                 fatalError("###\(#function): Failed to load persistent stores:\(error)")             }         })         self.persistentContainer = container     } } iOS 16.2 Xcode 14.1 Similar issues I found here, but without any success: https://stackoverflow.com/questions/58215343/an-error-occurring-during-core-data-persistent-store-migration-in-ios-13 https://stackoverflow.com/questions/51800871/ios-app-crashing-on-launch-screen-due-to-core-data-migration Please help me to figure out how can I do this migration?
Posted
by Taras_C.
Last updated
.
Post not yet marked as solved
6 Replies
948 Views
How to play gif in widget? "网易云音乐" and "one widget" can play gif in the widget. can anyone guide me. Thank you
Posted
by fwzhou.
Last updated
.
Post not yet marked as solved
6 Replies
3.6k Views
After updating to xcode 12.5 and ios14.5, our app's widget is NOT appearing in "Search widgets" I tried to upload the bundle with bitcode disabled but that didn't help. Anyone else experiencing this issue?
Posted
by msarg.
Last updated
.
Post marked as solved
9 Replies
3.6k Views
I am developing a widget where I want the options to be dynamic. However, when I run the widget on device, long press it and tap 'Edit Widget', nothing really happens. The widget animates back and no configuration view opens. If I open the Console app on my Mac and check for errors from the device, I can see this error being logged: Can't create SBHWidgetConfigurationInteraction because missing widgetDescriptor (&lt;private&gt;) or widgetIntent ((null)) Have I somehow misconfigured my widget or my intents file? This was working but it suddenly stopped working recently, and I can't figure out what I did wrong. Edit: I think I've tried most of the 'usual' fixes. Cleaning and building again, restarting Xcode, restarting the device, deleting the app, etc.
Posted
by vrutberg2.
Last updated
.