4

I'm currently working on a simple app that displays data received over the network in a watchOS complication. Notably, this data is only relevant for ~30 minutes before a new network fetch is required.

I'd like to have the complication be up to date when the user unlocks their watch in the morning (this is a common use case presented by Apple).

Is it possible to receive some kind of background task when the user unlocks their watch? If I schedule a background task and the watch is locked and charging when the refresh happens, will the background task still fire? What techniques can I use to have data ready for the user when they wake up and unlock their watch? Is there documentation specifically focusing on background tasks when the watch is locked?

Emma K Alexandra
  • 464
  • 3
  • 15

2 Answers2

2

As far as I know, the watch works in its locked state only slightly differently from its unlock state.
One difference is the display of complications:
You can specify the privacy behaviour, i.e. what the clock face displays as complication (you can select what is displayed on the lock screen).
So, to my mind, it is possible to run background tasks as scheduled when the watch is locked and charging. Thus the data will automatically be ready when the watch is unlocked.
For this reason, there is no special documentation what happens when the watch is locked, except for some special cases, as what is displayed on the watch face in the locked state.

Reinhard Männer
  • 14,022
  • 5
  • 54
  • 116
0

I would use the app life cycle docs here, and quite possibly choose:

  1. in applicationDidEnterBackground(), I'd set a flag (time when the complication was last updated). I'd suggest you use a singleton, so that it's accessible anywhere in your app.

  2. then in applicationDidBecomeActive() i'd pick up the flag, compare it with the current time, and notify the active ViewController to refresh its data, if it's greater than 30 minutes.

  3. if the flag doesn't exist, because the app was terminated, or it's a first launch, then refresh anyway (set a 24h date in the past, to use the same logic as in 1/,2/)

if you want to make it more permanent, use NSDefaults to store the last time the complication was updated.

Alex
  • 1,581
  • 1
  • 11
  • 27
  • When unlocking the watch, does applicationDidBecomeActive() get called? I thought that was only when the app entered the foreground, ie the user specifically opened your app – Emma K Alexandra Dec 05 '19 at 16:02
  • I think applicationWillEnterForeground() is always followed by a call to applicationDidBecomeActive(), see here https://developer.apple.com/documentation/watchkit/working_with_the_watchos_app_life_cycle . I'm not sure when it is best to call your update code, but in a nutshell, you can simply use Apple's watchOs life cycle diagram, and set/get the time your complication was last updated (transition 'A', 'B' and 'C' in the docs), and react accordingly. – Alex Dec 06 '19 at 08:25