I have implemented a NSURLSession that runs in the background (so it can continue the task using the system deamon even when the app is suspended). The issue is that
-(void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
is never called. I need to know the response status so I can handle properly the upload failure. According to another post, an Apple engineer told that this delegate method is not called when the session is backgroundSession to prevent the app from waking. Any suggestion on how to solve this issue? The last URLSession delegate method called in my situation is:
-(void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
The URLSession:task:didCompleteWithError: method of NSURLSessionTaskDelegate should be called when your upload is done. Refer to the task.response object, which should be the NSHTTPURLResponse object.
I'm sure you're doing this, but the standard background upload task components are:
Make a background session:
NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.domain.app"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
Use the NSURLSession method uploadTaskWithRequest:fromFile: method:
NSURLSessionTask *task = [session uploadTaskWithRequest:request fromFile:fileURL];
[task resume];
With a background session, you must:
Use NSURLSessionUploadTask;
Use file-based rendition (you cannot use NSData based version);
Use delegate-based rendition
cannot use data tasks; (b) NSData rendition of the NSURLSessionUploadTask; nor (c) a completion block rendition of the NSURLSessionUploadTask.
With upload tasks, make sure to not call setHTTPBody of a NSMutableRequest. With upload tasks, the body of the request cannot be in the request itself.
Make sure you implement the appropriate NSURLSessionDelegate, NSURLSessionTaskDelegate methods.
Make sure to implement application:handleEventsForBackgroundURLSession: in your app delegate (so you can capture the completionHandler, which you'll call in URLSessionDidFinishEventsForBackgroundURLSession).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With