Question

I am working on app that allows the user to take images and videos which are saved in the device initially. These need to be uploaded to the server whenever the device is connected to network(mobile data or wifi).

Now if I use NSURLSessionUploadTask, the data is uploaded in the background also but if there is no network, I receive a callback at the -didCompleteWithError: delegate and now the task is over. Now how can I resume the task when the device has network connection.

I want to do something like check reachability and if the device is reachable begin upload tasks.

One way I can think of is using Background Fetch to detect connection and schedule upload tasks.

This would be an enterprise app, So no approval is required.

Following is the code

NSURLSessionConfiguration *config = [NSURLSessionConfiguration         
backgroundSessionConfiguration:@"background" ];

NSURLSession *upLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self     
delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://www.t9l.com/rest/test/httprawdata"];      
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
NSString* str=@"nitin=asd";
[request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];

self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:filePath] ;

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

[self.uploadTask resume];
Was it helpful?

Solution

Your background uploads should work across network flakiness. If you get back an error state for one of your uploads in -didCompleteWithError:, you can just queue the same upload again. It won't matter if you are on the network when you do this, the OS should take care of uploading when it can/wants-to.

Background fetch comes when it comes, though plugged-in and on-wifi are good kick-offs. You'll surely have some connectivity when the fetch callback occurs. You should be able to queue background upload tasks during the fetch callback.

You could also register for the "lite" version of background geofencing, which will background notify you whenever a new network is detected or the cell tower switches. Cf. -[CLLocationManager startMonitoringSignificantLocationChanges].

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