Question

I need to upload files in the background with other HTTP POST requests before and after each upload.

Previously I was using beginBackgroundTaskWithExpirationHandler which was working perfectly till iOS 6 but from IOS 7 it is restricted for approx 180 seconds only which is a concern.

I have read the documents regarding NSURLSession were in we have Background transfer service. But the problem with this is it only allows upload and download in background. It doesn't allow me to make POST request after every upload in the background.

So is there any way to make the POST request along with the background uploads?

Any hint in the right direction would be highly appreciated.

Was it helpful?

Solution

I think you can use NSURLSessionDownloadTask to send a POST.

IMO, download task doesn't mean it is used for download. it means the response of your POST request (json/xml) will be downloaded to a local file. Then you can open that file and parse it to get the request.

if you want you can even use a NSURLSessionDownloadTask to upload files to S3. and the s3 response will be 'downloaded' to a local file..

for more information, see this question in the apple developer forum https://devforums.apple.com/thread/210515?tstart=0

OTHER TIPS

I successfully round-trip a vanilla http call during a background task's callback, in production code. The callback is:

-[id<NSURLSessionTaskDelegate> URLSession:task:didCompleteWithError:]

You get about 30 seconds there to do what you need to do. Any async calls made during that time must be bracketed by

-[UIApplication beginBackgroundTaskWithName:expirationHandler:]

and the "end task" version of that. Otherwise, iOS will kill your process when you pop the stack (while you are waiting for your async process).

BTW, don't confuse UIApplication tasks (I call them "app tasks") and NSURLSession tasks ("session tasks").

If you use uploadTaskWithRequest:fromData:completionHandler: you can make your HTTP POST request from the completion handler block:

[backgroundSession uploadTaskWithRequest:request fromData:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    if (httpResponse.statusCode == 200) {
        NSMutableURLRequest *postRequest = [NSMutableURLRequest requestForURL:[NSURL URLWithString:@"http://somethingorother.com/"]];
        request.HTTPMethod = @"POST";
        .
        .
        .
        NSURLResponse *postResponse;
        NSError *postError;
        NSData *postResponseData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:&postResponse error:&postError]; 
        // Check postResponse and postError to ensure that the POST succeeded
    }
}];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top