Correct way to display content of today's widget

I am working on extending the view today with some custom view elements that I have not configured in the interface builder.

Now I'm wondering where the correct point in the lifecycle is to initiate the content of the widget.

I read about updating content in widgetPerformUpdateWithCompletionHandler

, so I implemented a check for new updates that should show up in the view.

But my observations showed me that the method is called before viewDidAppear

and therefore there is no update to update. Also, I saw that the widget stays in memory for a while, so I can have a certain object in widgetPerformUpdateWithCompletionHandler

, the contents of which I can update and use in viewDidAppear

, but this is not the case (it is loaded every time)

So what is the correct way to write the content to disk in widgetPerformUpdateWithCompletionHandler

, can I depend on what's in memory, or just ignore and update every download?

+3


source to share


1 answer


The TodayViewController.m

-viewDidLoad()

method is called every time you open a notification. So when you view the Today widget, it calls -viewDidLoad()

. So, you do your setup in -viewDidLoad()

. If you don't want to check the previous state.

Straight from a blog that helps create a Today widget with real-time data:

Create a widget today

Caching We can use NSUserDefaults to save the estimated used space between runs. The widget's lifecycle is short, so if we cache this value, we can set up the UI with an initial value and then calculate the actual value.

Edit:

From Apple's documentation it says that

To keep your widget up to date, the system sometimes captures snapshots of your widgets. When the widget becomes visible again, the last snapshot is displayed until the system replaces it with a live version of the view.



It also states that we can get information about the status and snapshot widgets from the Notification Center.

Not sure about this, but he claims the below method is used by both widgets and the containing app to validate its content. There is no detailed information on how to get a snapshot of the widget.

  func setHasContent(_ flag: Bool,
forWidgetWithBundleIdentifier bundleID: String!)

      

NCWidgetController setHasContent

Edit 2: Using NSUserDefaults in an extension:

  • You have two files .entitlements

    , one for the host application and one for the extension, add below key to both files

    <key>com.apple.security.application-groups</key>
    <array>
        <string>group.YourExtension</string>
    </array>
    
          

  • You can see that the value for the key group.YourExtension

    is the shared key for the host application and the extension application

  • Save your data with group.YourExtension

    inNSUserDefaults

+2


source







All Articles