我在许多应用程序上使用此代码,并且没有遇到任何问题(请注意,我正在使用 AFJSONRequestOperation 和 AFRestClient)
设置请求
// I have a shared singleton in a separate file APIClient.h
AFRESTClient *httpClient = [APIClient sharedClient];
NSURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:method parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData> formData)
{[formData appendPartWithFileData:imageData
name:@"image"
fileName:@"image.png"
mimeType:@"image/png"];
}];
然后进行操作,
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
我的进度块
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
CGFloat progress = ((CGFloat)totalBytesWritten) / totalBytesExpectedToWrite * 100;
[SVProgressHUD showProgress:50 status:[NSString stringWithFormat:@"%0.1f %%", progress]];
}];
success 块(我的 API 返回 stat -ok 或失败,然后是数据(与 flickr API 相同)
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"response string: %@", operation.responseString);
NSString *resultStat = [response objectForKey:@"stat"];
if ([resultStat isEqualToString:@"ok"]) {
//success
// do something with your data that is returned from the API
} else {
//error
NSLog(@"Data Error: %@", response);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", [error localizedDescription]);
}];
[httpClient enqueueHTTPRequestOperation:operation];