AFNetworking如何检查上传操作是否已完成或失败

时间:2011-11-07 13:50:01

标签: objective-c upload notifications afnetworking

如何检查AFNetworking是否已完成文件上传?我怎么能检查是否有问题?

这是我的代码:

AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://server"]];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:[fieldName text] forKey:@"name"];
[parameters setObject:[fieldSurname text] forKey:@"surname"];

NSMutableURLRequest *myRequest = [client multipartFormRequestWithMethod:@"POST" path:@"/upload.php" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:[[AttachedFile sharedAttachedFile]dataToSend] mimeType:@"image/jpeg" name:@"attach"];
}];

AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:myRequest] autorelease]; 
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
    NSLog(@"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];

queue = [[[NSOperationQueue alloc] init] autorelease];
[queue addOperation:operation];

我应该实现哪个方法(和委托)?

谢谢!

2 个答案:

答案 0 :(得分:3)

使用

[AFHTTPRequestOperation HTTPRequestOperationWithRequest:myRequest
                                                success:(void (^)(id object))success 
                                                failure:(void (^)(NSHTTPURLResponse *response, NSError *error))failure];

而不是

AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:myRequest] autorelease]; 

当您的文件完全上传时,将调用成功块。如果出现问题,则调用失败块。

答案 1 :(得分:0)

不推荐使用

HTTPRequestOperationWithRequest ,最好在AFHTTPRequestOperation实例上使用 setCompletionBlockWithSuccess:failure

AFNetworking Uploading a file

检查mattt的答案