2

我正在开发一个上传多个文件的应用程序。对于上传,我使用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];

谁能给我处理这种情况的建议。

谢谢。

4

1 回答 1

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 完成的),这样您的操作就不会被释放

于 2013-05-30T18:58:40.657 回答