问题
I am finding that my Notification Center widget does not reload very often. Because of this, out of date data being presented. I have not been able to find a way to get the widget to refresh every time I open the Today view. I have seen apps such as NBA Gametime that are able to update every time I pull down to see the widget.
How can I get this functionality in my app?
回答1:
Based on my own experimentation and also reports in this SO thread, it appears that the TodayViewController.viewDidLoad()
function gets called every time the Today/Notifications area gets opened. More specifically, @Karl Monaghan reported in a comment that the iOS 8.1 release notes have the following to say:
The schedule and intended use of widgetPerformUpdateWithCompletionHandler: is intended as a convenient home for all data/model update logic. If implemented, the system will call at opportune times for the widget to update its state, both when Notification Center is visible, as well as in the background. An implementation is required to enable background updates. It’s expected that the widget will perform the work to update asynchronously and off the main thread as much as possible.
So, to answer your question:
- I don't think we'll ever really know how often the
widgetPerformUpdateWithCompletionHandler
method gets called, and I think Apple prefers it that way - The
viewDidLoad
function does get called every time the widget is displayed, so it's possible that you could put a call to the update function inside of that method. Or you could just put whatever updates you need to be shown in the widget inside of that function, although I don't know what kind of impact that will have on app performance.
Hope this helps.
Update
I've also found that either one of initWithCoder
or initWithNibName
seems to get called every time the widget is displayed on the screen, so it's possible that you could put calls to update your widget in those files, but if I recall correctly the view is not actually instantiated at this time so it's better NOT to put your code to update your widget in these functions.
回答2:
In your widgetPerformUpdateWithCompletionHandler
you need to to let your widget know that it needs to update. Apple Docs
-(void)widgetPerformUpdateWithCompletionHandler:(void (^)(NCUpdateResult))completionHandler {
// Perform any setup necessary in order to update the view.
// If an error is encoutered, use NCUpdateResultFailed
// If there's no update required, use NCUpdateResultNoData
// If there's an update, use NCUpdateResultNewData
completionHandler(NCUpdateResultNewData);
}
来源:https://stackoverflow.com/questions/30009441/how-to-frequently-update-today-widget-in-notification-center