What's the best approach to make sure that an upload works?
I need to upload images, to a server and make sure, that the upload has worked. If, for whatever reason, the upload did not work, I'll have to retry later.
Currently, I'm using NSUrlSession to upload the image:
- (void)didCreateSignature:(UIImage *)image {
BLog();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageFile = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"test.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:imageFile atomically:YES];
while (![[NSFileManager defaultManager] fileExistsAtPath:imageFile]) {
[NSThread sleepForTimeInterval:.5];
}
NSURLSession *session = [self backgroundSession];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.uploadUrl]];
[request setHTTPMethod:@"POST"];
[request addValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:signatureFile]];
[uploadTask resume];
}
Now let's assume that the user does not have internet connection, then the delegate will be fired:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
BLog();
if (error == nil)
{
NSLog(@"Task: %@ completed successfully", task);
}
else
{
NSLog(@"Task: %@ completed with error: %@", [task originalRequest], [error localizedDescription]);
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
});
}
}
According to the Apple Documentation you should retry later if the Reachability status has changed. So i was thinking of adding these tasks to an Array and start each task again once the Internet connection has become available.
Is this the right approach?
And what happens, if the user closes the app (via TaskManager). How can I make sure that these tasks will be resumed ?