[英]iOS 7 background upload and POST requests

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

每次上传之前和之后,我需要在后台上传文件和其他HTTP POST请求。

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.

之前我使用的是beginBackgroundTaskWithExpirationHandler,它在iOS 6之前运行得很好,但是从ios7开始,它的运行时间被限制在180秒左右,这是个问题。

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.


3 个解决方案



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




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:

如果您使用uploadTaskWithRequest:fromData:completionHandler:您可以从完成处理程序块中创建HTTP POST请求:

[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:@""]];
        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



© 2014-2019 粤ICP备14056181号