Reputation: 2486
I'm working on a today view extension with some custom view elements which I don't set up in interface builder.
Now I'm wondering where the right point in the lifecycle is to init the widget content.
I read about updating the content in widgetPerformUpdateWithCompletionHandler
so I implemented a check for new updates which should about the view.
But my observations showed me that the method is called before viewDidAppear
and so there is no view to update.
Also I tought the widget stays in memory for a while so that I can have a certain object in widgetPerformUpdateWithCompletionHandler
whose content I can update and use in viewDidAppear
but this isn't the case (it loads every time)
So what is the correct way: write content to disk in the widgetPerformUpdateWithCompletionHandler
, can I depend on something that is in memory or just ignore and refresh on every load?
Upvotes: 3
Views: 1926
Reputation: 23053
In TodayViewController.m
-viewDidLoad()
method is called each time you open notification. So when ever you check Today widget it will call -viewDidLoad()
. So you do your customisation in -viewDidLoad()
. Unless you don't want to check previous state.
Straight from a blog which helps a create Today widget with real time data:
Caching We can take advantage of NSUserDefaults to save the calculated used space between launches. The lifecycle of a widget is short so if we cache this value, we can set up the user interface with an initial value and then calculate the actual value.
Edit:
From Apple documentation it state that
To help your widget look up to date, the system occasionally captures snapshots of your widget’s view. When the widget becomes visible again, the most recent snapshot is displayed until the system replaces it with a live version of the view.
It is also state that from Notification center, We can get widget details of state and snapshot.
Not sure with this, but it state that below method is used by both widget and containing app to check its content. There is no much details about how to get widget snapshot.
func setHasContent(_ flag: Bool,
forWidgetWithBundleIdentifier bundleID: String!)
NCWidgetController setHasContent
Edit 2: Use of NSUserDefaults in extension:
You have two .entitlements
files, one for host app and second for the extension app, add below key in both files
<key>com.apple.security.application-groups</key>
<array>
<string>group.YourExtension</string>
</array>
You see the value for key is group.YourExtension
it is shared
common key for both host app and extension app
Save your data using group.YourExtension
in NSUserDefaults
Upvotes: 2