I have done some research on the iOS widget refresh mechanism:
1 With containing app in the foreground, the widget refresh is not limited
Read the apple developer docs, I learned that the widget refresh is controlled by the WidgetKit budgets. As it states:
For a widget the user frequently views, a daily budget typically includes from 40 to 70 refreshes
But in the following cases, the reload doesn’t count against the widget’s budget:
- The widget’s containing app is in the foreground.
- The widget’s containing app has an active audio or navigation session.
- The system locale changes.
- Dynamic Type or Accessibility settings change.
2 We can use WidgetCenter.shared.reloadTimelines
to refresh widget from containing app
The same doc says:
In the game widget example above, if the app receives a push notification indicating a teammate has given the character a healing potion, the app can tell WidgetKit to reload the timeline and update the widget’s content.
3 I have seen some great implementation on this
Apps like LiveIn gives me a smooth user experience with widget refresh timely when I got a post from my friends (as long as the containing app is in the foreground, guess they can improve this with Background Refresh).
This product is not limited by the daily 40 to 70 refreshes budget limitation, and I get a little delay (little enough to be ignored) between the picture display in containing app and the widget.
4 But I'm still stuck here
But when I tried to build an app using the above API WidgetCenter.shared.reloadTimelines
or WidgetCenter.shared.reloadAllTimelines
to notify the widget to refresh with data stored in UserDefaults, my widget does not respond to the API call timely. Sometimes, it may be stuck for more than 10 minutes, which is a terrible case far far away from the product I mentioned above.
5 Some hack attempts
I have looked through so many Stackoverflow QAs & blogs and do find some tricky things in the iOS widget. For example, the View._clockHandRotationEffect(.secondHand, in: .current, anchor: .center)
API can be used to refresh the widget view without limits (usually used to build clock based applications).
But it seems to have nothing to do with the message notification between the containing app and the widget (or it is just I have not figured it out yet).
6 My question
So here comes my question. As some apps existing on the iOS store already have the capability to notify widgets timely, why can I still not get the smooth user experience guided by the official documentation? Do I miss some things important here, or they are just using other private APIs that are out of my sight?
The code is not complex and the Xcode signing is annoying, so I do not prepare a minimal project to reproduce this. You may take pawello2222/WidgetExamples as a demo if you want to give it a try. Any hints or clues will be highly appreciated!