How to get backgroundSession NSURLSessionUploadTas

2020-05-19 08:10发布

问题:

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

回答1:

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:

  1. Make a background session:

    NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.domain.app"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
  2. 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.

  3. 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.

  4. Make sure you implement the appropriate NSURLSessionDelegate, NSURLSessionTaskDelegate methods.

  5. Make sure to implement application:handleEventsForBackgroundURLSession: in your app delegate (so you can capture the completionHandler, which you'll call in URLSessionDidFinishEventsForBackgroundURLSession).