WatchOS Updating complications with a background task

224 views Asked by At

I have an apple watch app that receives data from a companion iPhone app. The iPhone app sends regularly data to the watch using the Watch Connectivity framework:

try? WCSession.default.updateApplicationContext(["kAppContext": data])

The watch then receives the payload at:

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        if let data = applicationContext["kAppContext"] as? Data {
           //Trigger push notification. Will be observed by the CLKComplicationDataSource
        }
}

In the CLKComplicationDataSource I am listening to the notification and updating the complication:

let server = CLKComplicationServer.sharedInstance()
if let complications = server.activeComplications {
       for complication in complications {
             server.reloadTimeline(for: complication)
        }
}

Nothing new under the hood, when the watch is in foreground the complication gets updated with no issues. When the apple watch is in background, it stops receiving any updates in: func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any])

and thus not updating the complication.

Now I am trying to update the complication in the background with a background refresh task, in the Extension Delegate:

func applicationWillResignActive() {
  scheduleTask()
} 
    
func scheduleTask() {
   WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: Date().addingTimeInterval(5), userInfo: nil) { error in
 if error != nil {
      print("Error adding schedule update")
 }
}

And now the question. For some reason, after 1 schedule background refresh, the method: func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) gets called properly, and almost all the data send from the phone reach the watch, and the complication gets updated.

Why is this happening? It does what I want but I don't know why. Why just adding one background app refresh task makes the data from the phone to start coming through? I have not found a description of such behaviour in the apple documentation.

Thanks

0

There are 0 answers