Ios 为什么在使用AFNetworking库将wave文件上载到服务器时要获得二进制响应
我需要在服务器上上传一个wave文件,服务器会返回该文件的URL 我用过这个密码Ios 为什么在使用AFNetworking库将wave文件上载到服务器时要获得二进制响应,ios,iphone,afnetworking,Ios,Iphone,Afnetworking,我需要在服务器上上传一个wave文件,服务器会返回该文件的URL 我用过这个密码 - (void)callUploadWS { NSString *vidURL = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"]; NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:vidURL]]; NSURL *url = [NSURL
- (void)callUploadWS
{
NSString *vidURL = [[NSBundle mainBundle] pathForResource:@"alarm" ofType:@"wav"];
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:vidURL]];
NSURL *url = [NSURL URLWithString:@"http://6.6.237.190"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
// NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"Romantic.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/recorder/convert.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:videoData name:@"file" fileName:@"speech.wav" mimeType:@"audio/vnd.wave"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
// [httpClient enqueueHTTPRequestOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"Success : %@",responseObject);}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
NSLog(@"error: %@", error.userInfo);
}];
[operation start];
}
为什么会给出二进制响应?您必须像这样将responseObject转换为NSString
NSString *responseString=[NSString stringWithUTF8String:[responseObject bytes]];
@Gagan Kumar给出了一个非常好的答案,但它的一半是代码。它将把json响应转换为字符串。
因此,您无法从中获取字典,也无法解析文件URL。为此,必须使用以下代码将字符串重新序列化为json
NSString *responseString=[NSString stringWithUTF8String:[responseObject bytes]];
NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (e) {
NSLog(@"error : %@",e);
}else{
NSLog(@"JSON : %@",JSON);
}
这将返回可解析的json对象。希望能有所帮助。就这样了。但问题是我为什么要这样做?我用AFNetworking来下载和上传我的文本,但从来没有用过这个。我不知道你是如何使用它的,但我总是用这种方式
NSString *responseString=[NSString stringWithUTF8String:[responseObject bytes]];
NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: [responseString dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (e) {
NSLog(@"error : %@",e);
}else{
NSLog(@"JSON : %@",JSON);
}