I have some misunderstanding in using NSURLSession
framework, that's why I decided to write small app from scratch without AFFramework/Alamofire.
I have an API that requires following steps to upload file:
- POST file data
- Get response (JSON)
- Post some json fields to
api/save
I have a background session with such config:
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("myBackground")
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
I've implemented 2 methods:
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)
where I aggregate all data
and
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?)
where I tranform this data to response object. This response object if VERY important for me.
Everything works fine, while app is in foreground, but I have problems in background.
Case 1
App crashed right after I've started to upload data. According to WWDC I need to implement
func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void)
and call this handler in didCompleteWithError
method. But before calling this method I need to call api/save
with data from upload response.
How can I get this data?
Case 2
Mostly similar case. User stops app while upload is in progress. Than loads app in few seconds, while session works with my task. Now session calls didReceiveData
, but of course, some of data is missing. What should I do in such case? How to restore response data?
URLSessionDidFinishEventsForBackgroundURLSession
with no luck. I restarted bg session and gotURLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData)
I got following data:session: <__NSURLBackgroundSession: 0x1668c060> dataTask: <__NSCFBackgroundUploadTask: 0x165ade60>{ taskIdentifier: 1 } data: 0
which crash my app, when I try to append data – Drillmaster