I am developing a app which upload multiple files. For uploading, I use AFHTTPRequestOperation
. It successfully works, But If I lock and after it unlock the screen,then It stop uploading files.
My code for upload file is here
NSUserDefaults *defaultUser = [NSUserDefaults standardUserDefaults];
NSString *userId = [defaultUser stringForKey:@"UserId"];
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",UploadURL,userId]]];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: data name:@"f" fileName:[NSString stringWithFormat:@"%d_image.jpeg",rand()] mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", [operation error]);
if(error.code == -1001){
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Error!"
message:@"The request timed out." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[myAlert show];
}
}];
[operation start];
Can anyone give me suggestion for handle this situation.
Thanks.
0
|
(1) Add this code:
(2) Change this line:
to
(3) Keep a strong reference to your AFHTTPClient (this is typically done for AFHTTPClient with the singleton pattern) so that your operations don't get deallocated |
How do I keep requests running in the background after the app has been dismissed?
As of AFNetworking 1.0RC1, AFURLConnectionOperation
has asetShouldExecuteAsBackgroundTaskWithExpirationHandler:
method that can be used to have operations continue when an app is dismissed and enters the background:
[self setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
// Clean up anything that needs to be handled if the request times out
// It may be useful to initially check whether the operation finished or was cancelled
}];