How to handle complication update with urlSession

At https://developer.apple.com/documentation/clockkit/updating_your_complication there is this information:

Also, there’s no guarantee about the order in which the system calls URLSession:downloadTask:didFinishDownloadingToURL: and handleBackgroundTasks:. Your app must handle all possible cases.

In example code I've seen online, people usually receive a call to handleBackgroundTasks with a WKURLSessionRefreshBackgroundTask, store that value, then receive a didFinishDownloadingToURL, process the download, and then call setTaskCompletedWithSnapshot with the stored value.

If didFinishDownloadingToURL occurs first, and then the handleBackgroundTasks with a WKURLSessionRefreshBackgroundTask occurs second, then we presumably need to call setTaskCompletedWithSnapshot immediately. How do we know that's the right thing to do? Are we supposed to observe timing to understand that these two seperate calls are related? Are we supposed to maintain our own state machine to know that we are about to receive a pair of calls in unknown order? What's the right way to structure our behavior here?

thanks

Answered by Frameworks Engineer in 614134022
There are two possible scenarios:

(1) NSURLSession daemon launched your app in the background

You will receive WKURLSessionRefreshBackgroundTask first before delegate messages like didFinishDownloadingToURL.

(2) Your app is launched for an unrelated reason and happens to receive NSURLSession delegate messages

In this case, your delegate will drain all messages from NSURLSession daemon. Unless your app has more outstanding work, it won't receive WKURLSessionRefreshBackgroundTask in the future.

If these are not the behavior you observed, please file a bug through Feedback Assistant.
There are two possible scenarios:

(1) NSURLSession daemon launched your app in the background

You will receive WKURLSessionRefreshBackgroundTask first before delegate messages like didFinishDownloadingToURL.

(2) Your app is launched for an unrelated reason and happens to receive NSURLSession delegate messages

In this case, your delegate will drain all messages from NSURLSession daemon. Unless your app has more outstanding work, it won't receive WKURLSessionRefreshBackgroundTask in the future.

If these are not the behavior you observed, please file a bug through Feedback Assistant.
How to handle complication update with urlSession
 
 
Q