2013-01-17 23 views
2

我正在開發一個上傳多個文件的應用程序。 對於上傳,我使用AFHTTPRequestOperation。它成功地工作,但如果我鎖定並解鎖屏幕後,它停止上傳文件。AFHTTPRequestOperation在待機模式後不起作用

我要上傳文件代碼是在這裏

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

誰能給我建議,對於處理這種情況。

謝謝。

+0

這與setShouldExecuteAsBackgroundTaskWithExpirationHandler有關,但我不能100%確定代碼必須去哪裏 – Nick

+0

http://stackoverflow.com/a/9164755/1702413 – TonyMkenu

+0

@TonyMkenu這是NSURL連接,而不是AFNetworking? – Nick

回答

2

(1)添加以下代碼:

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

(2)更改此行:

[operation start]; 

[client enqueueHTTPRequestOperation:operation]; 

(3)保持的強引用您的AFHTTPClient (這通常是用單例模式爲AFHTTPClient完成的),這樣你的操作就不會被釋放掉了。

+0

setShouldExecuteAsBackgroundTaskWithExpirationHandler沒有被調用,我需要一些幫助 – ram