Communication between iOS app & Widgets for iOS 14
Yes this is possible using one of the WidgetCenter
APIs to reload your timeline.
...
// make API call
// store data in shared storage that the Widget uses
WidgetCenter.shared.reloadAllTimelines()
// OR
WidgetCenter.shared.reloadTimelines(ofKind: "WidgetKind")
Note that it's most likely preferred to use reloadTimelines(ofKind: "WidgetKind")
since it will only reload the timelines of a specific widget. "WidgetKind" can be found in your WidgetConfiguration definition
Can iOS14 widget requests main app to update its data?
There's no way for a Widget to tell its parent App to refresh its data.
You can either:
- fetch data directly in the Widget - see: How to refresh Widget data?
- enable background notifications in the App (see How to run code when your app is terminated) and, when received one, force the Widget to refresh its timeline using:
WidgetCenter.shared.reloadAllTimelines()
In reality it's probably better to just fetch data directly in the Widget. This way you can fetch only the necessary data - Widget views usually display a lot less information than App views.
Sharing Data with AppGroup
- Save data to
UserDefaults
in your main App:
UserDefaults(suiteName: <your_app_group>)!.set("test", forKey: "test")
- Read data from
UserDefaults
in your Widget:
let testStr = UserDefaults(suiteName: <your_app_group>)!.string(forKey: "test")
If you want to save other types see:
- How can I use UserDefaults in Swift?
Related Topics
How to Check If a String Contains Another String in Swift
How to Convert Unix Epoch Time to Date and Time in iOS Swift
Swipe-Able Table View Cell in iOS 9
Why Is 'Nil' Not Compatible With 'Unsafepointer≪Cgaffinetransform≫' in Swift 3
How Does Collisionbitmask Work? Swift/Spritekit
How to Make a Swiftui List Scroll Automatically
Uitableview With More Than One Custom Cells With Swift
Swift Protocol Extension Method Is Called Instead of Method Implemented in Subclass
How to Detect If an Skspritenode Has Been Touched
What Does "@Uiapplicationmain" Mean
Getting "File Not Found" in Bridging Header When Importing Objective-C Frameworks into Swift Project