Apple Sample Code for WatchKit Extension Background Refresh
For anyone who may find this, there were 2 problems that I saw, both with the URLSession scheduling. With these changes, I think the Apple sample code actually works, at least on the simulator.
-The sampleDownloadURL
needs to be secure, so a URL with HTTPS is necessary. This one works: https://api.weather.gov/points/42.3584,-71.0598/forecast
-It looks to me like the delegate for the URLSession
was never set to self
, so the following change fixed that:
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
The following working (although less complete) code was very helpful: What's New in watchOS 3: Background Tasks
Edit: One more issue that may occur is that the tasks are completed immediately after they are received. In practice, they should be saved (in a local variable, for instance) and then completed after all processing for that task is complete. For this code, I think that means hanging onto the WKApplicationRefreshBackgroundTask
and not calling setTaskCompleted()
on it until right after the call to scheduleSnapshot
.