Background session sequencing at startup

When my app starts up, it queries any existing tasks using


[_urlSession getTasksWithCompletionHandler:^(NSArray<NSURLSessionDataTask *> * _Nonnull dataTasks, NSArray<NSURLSessionUploadTask *> * _Nonnull uploadTasks, NSArray<NSURLSessionDownloadTask *> * _Nonnull downloadTasks) {

if(uploadTasks.count)

{


....

// I only ever run one task at a time which is why I'm pulling just the first one.

_lastUploadTask = uploadTasks[0];

self.state = Uploading;

}



Later I have

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

{

assert(_lastUploadTask == task);


I have a crash report from the field where this assert has been hit. Unfortunately I have very little extra information...


1) Could didCompleteWithError be called on a task AFTER I call getTasksWithCompletionHandler but BEFORE the completionHandler is called? The more I think about it, the more plausible it seems, but it would be useful to have it confirmed.


2) If this did happen, would the task be present in the uploadTasks parameter of the completionHandler, or would it absent (as I would expect).

Accepted Reply

1) Could didCompleteWithError be called on a task AFTER I call getTasksWithCompletionHandler but BEFORE the completionHandler is called?

Yes. The API makes no guarantees about the order in which delegate callbacks are made, so it’s possible to get

-URLSession:task:didCompleteWithError:
before the
-getTasksWithCompletionHandler:
block runs.

2) If this did happen, would the task be present in the

uploadTasks
parameter of the completionHandler, or would it absent (as I would expect).

Honestly, I suspect that either is possible. When I last tackled this problem I wrote my code to not rely on this aspect of

-getTasksWithCompletionHandler:
. I explained my logic in this thread.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

1) Could didCompleteWithError be called on a task AFTER I call getTasksWithCompletionHandler but BEFORE the completionHandler is called?

Yes. The API makes no guarantees about the order in which delegate callbacks are made, so it’s possible to get

-URLSession:task:didCompleteWithError:
before the
-getTasksWithCompletionHandler:
block runs.

2) If this did happen, would the task be present in the

uploadTasks
parameter of the completionHandler, or would it absent (as I would expect).

Honestly, I suspect that either is possible. When I last tackled this problem I wrote my code to not rely on this aspect of

-getTasksWithCompletionHandler:
. I explained my logic in this thread.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"