Let's say I have a running NSURLSessionUploadTask
. What happens to the pending request if the app is killed or crashes during that timeframe? Will the task still complete or is it also terminated?
-
NSURLSession documentation could help you https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/UsingNSURLSession.html#//apple_ref/doc/uid/TP40013509-SW6 – agy Aug 04 '15 at 07:40
-
1If it did help me, I wouldn't ask, would I? Actually nothing in there touches on how it behaves if the app is terminated in an uncontrolled manner. – Aug 04 '15 at 08:52
-
The background task is canceled if the user kills the app. Check this https://stackoverflow.com/questions/40613525/nsurlsession-with-background-configuration-and-app-killed-by-user – Ingweland Apr 06 '20 at 16:37
2 Answers
This is from memory, so take it with a grain of salt. IIRC, it depends on the task type, how far along the task is in its progress and whether you provided a body data object or a body stream.
If you are using a non-background session, the request is canceled.
If you are using a background session:
If you provided a body data object via the URL request object or as part of creating an upload task, the upload should complete, because the session basically sends that data object to a helper process via XPC, and the helper can handle the upload. Of course, if the data object doesn't make it to the helper before the crash, it won't finish.
If you provided the body through a stream, obviously it won't complete unless the upload phase is finished, because your app won't be there to provide the data.
If the upload finishes, in iOS, the OS relaunches your app in the background to handle the received data; in OS X, nothing happens until the user relaunches your app, at which point the OS delivers the waiting data.
If you're using an upload task, the OS delivers the data to your app like a data task after the relaunch. Then, on iOS (only), it tells you that it has delivered all pending events, at which point your app must call the callback that the OS gave you when your app was first relaunched, to tell the OS that it is safe to kill your backgrounded app.
Note that if your app crashes while receiving the response data from an upload task, IIRC, your app won't get relaunched. If the actual results of the upload operation are critical for your app to have, use a download task to upload, and provide a body data object through the provided NSURLRequest object.

- 10,129
- 1
- 28
- 49
From Apple's Documentation.
If the system terminated the app while it was suspended, the system relaunches the app in the background.
It's under the "Recreate the Session If the App Was Terminated" section. It explains what happens and how to need to re-reate the session on app launch so background processes can get handled properly.

- 23,075
- 12
- 60
- 84