我正在开发一个上传多个文件的应用。
要上传,我使用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 :(得分: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完成的),这样您的操作就不会被解除分配