AFNetworking: AFHTTPRequestOperation doesn't work after stand by mode

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.



Answer

active oldest votes
up vote 0 down vote

(1) Add this code:

[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{ // Handle iOS shutting you down (possibly make a note of where you // stopped so you can resume later) }];

(2) Change this line:

[operation start];

to

[client enqueueHTTPRequestOperation:operation];

(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



转载:  http://stackoverflow.com/questions/14375173/afhttprequestoperation-doesnt-work-after-stand-by-mode





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
}];



参考:https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ

你可能感兴趣的:(AFNetworking: AFHTTPRequestOperation doesn't work after stand by mode)