【发布时间】:2012-11-07 22:15:01
【问题描述】:
我正在使用AFNetworking 并希望将NSData 对象上传到我的服务器。我正在尝试上传到我们的 SOAP 服务器,所以我有已转换为 NSData 对象的 XML。由于某种原因,以下方法不起作用:
// Back to NSData
NSData *convertedFile = [xml dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:siteConfiguration.soapURL];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFormData:convertedFile name:assetCreation.name];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
// Progress
float totalProgress = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
progress(totalProgress, totalBytesWritten, totalBytesExpectedToWrite);
if (totalBytesExpectedToWrite == totalBytesWritten) {
completion();
}
}];
[operation start];
但是当不使用 multipartFormRequestWithMethod 块时,它确实可以工作并且文件已正确上传,但没有显示任何进度,因为回调只调用了一次:
// Back to NSData
NSData *convertedFile = [xml dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:siteConfiguration.soapURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody:convertedFile];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
// Progress
float totalProgress = (float)totalBytesWritten/(float)totalBytesExpectedToWrite;
progress(totalProgress, totalBytesWritten, totalBytesExpectedToWrite);
if (totalBytesExpectedToWrite == totalBytesWritten) {
MatrixAsset *asset = [[MatrixAsset alloc] init];
completion(asset);
}
}];
[operation start];
看来我的服务器真的想用我的NSData 对象发送HTTPBody。是否可以对AFNetworking 进度回调做同样的事情?
【问题讨论】:
-
你试过
[formData appendPartWithFileData:convertedFile name:assetCreation.name];而不是[formData appendPartWithFormData:convertedFile name:assetCreation.name];吗? -
我也将
mimeType:设置为text/xml -
没有一个名为 [formData appendPartWithFileData:convertedFile name:assetCreation.name] 的方法,至少在最新版本的 AFNetworking 中没有。我需要将它作为我认为的表单发送,因为它是发送到我们的 SOAP 服务器并且还有其他字段数据正在发送。
-
将内容类型设置为 text/xml 没有帮助。我用过:[request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"];它停止了进度回调的工作。
标签: objective-c ios afnetworking nsmutableurlrequest