What is the purpose of widgetPerformUpdateWithCompletionHandler in iOS 8 Today Widget?

ktzhang picture ktzhang · Aug 6, 2014 · Viewed 8.7k times · Source

Been looking around for an answer but everything seems vague or unclear.

Anyways, just want to know what the purpose of the function:

widgetPerformUpdateWithCompletionHandler

does in the today widget.

According to Apple:

This method is called to give a widget an opportunity to update its contents and redraw its view prior to an operation such as a snapshot. When the widget is finished updating its contents (and redrawing, if necessary), the widget should call the completion handler block, passing the appropriate NCUpdateResult value.

When does the snapshot ever happen? Whenever I debug the extension, widgetPerformUpdateWithCompletionHandler always gets called after loadView. So what is the purpose of explicitly reloading information in this method when I already load the information in loadView?


According to this website: http://www.karlmonaghan.com/tag/today-widget/

In the TodayViewController, there are two places that need to load data from the network – when the widget is created and when widgetPerformUpdateWithCompletionHandler is called. For the former, I load posts in viewDidLoad, so that they should be ready by the time the widget displays. When iOS thinks the widget will be displayed to the user after it has been first displayed, widgetPerformUpdateWithCompletionHandler is called giving the widget a chance to update the posts displayed.

Same question as above.

Answer

Karl Monaghan picture Karl Monaghan · Aug 13, 2014

A widget is not created every time you view the notification center so loadView won't be called every time it is displayed. The notification center instead calls widgetPerformUpdateWithCompletionHandler when it thinks the widget information needs to be updated. From my own debugging it does look like that when the widget is initially created widgetPerformUpdateWithCompletionHandler is called nearly straight away so you could just do all the loading in there but Apple recommends you start the loading process as early in the life cycle as possible.

If the information your widget displays never changes, then you don't have to do anything in widgetPerformUpdateWithCompletionHandler.