Question

Am trying to use NSURLSession for uploading Images to the server using POST. Each time i may have more than 10 Images with big size. What i want to do is, do the POST in backgroundSessionConfiguration so even if user close the app background uploading should not be stopped and after finish show a notification. When i use backgroundSessionConfiguration for NSURLSessionDownloadTask for downloading from server every thing work perfect. But when i try to use it for POST with NSURLSessionDataTask am getting below error

*** Terminating app due to uncaught exception 'NSGenericException', reason: 'Data tasks are not supported in background sessions.'
*** First throw call stack:

After i googling for this error i found that the we should not use backgroundSessionConfiguration with NSURLSessionDataTask. I would like to know how to achieve background uploading for POST.

Was it helpful?

Solution

try this.

NSURL *URL = [NSURL URLWithString:@"urlString"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSData *data = [NSData dataWithContentsOfFile:fileURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {}];
[uploadTask resume];

OTHER TIPS

If you want to use backgroundSessionConfiguration you can't use the completion block calls. The Apple docs are very confusing on this and other points. I have successfully implemented background uploads after many hours of frustration. Since there isn't much info on the internets, I've decided to document my work. https://medium.com/@KyleRStewart/zombie-uploads-with-ios-dd3b1f6b66 Hopefully this saves you some time.

@johny. Solution you proposed does not work if we want to support upload task in background. Correct way to support upload from background is using following method provided by Apple

*

/* Creates an upload task with the given request.  The body of the request will be created from the file referenced by fileURL */
*- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL;*

*

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top