我正在开发一个上传多个文件的应用程序。
对于上传,我使用 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];
任何人都可以给我处理这种情况的建议吗?
谢谢。
最佳答案
(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 完成的),以便您的操作不会被释放
关于iphone - AFHTTPRequestOperation 在待机模式后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14375173/