若是不是NSData就要想辦法把語音文件轉化爲NSData,而後才能上傳服務器。json
首先咱們拿到語音文件對應的NSData對象 NSData *voiceData = [message valueForKey:@"wavAudioData"]; //kHostURL爲開發者公司的APP對應的主域名,好比http://xxx.yyy.cn AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:kHostURL]]; manager.requestSerializer.timeoutInterval = 100; NSMutableDictionary *paras = [[NSMutableDictionary alloc]init]; [paras setValue:self.msgType forKey:@"msgType"]; //以file的形式上傳,這裏的key很重要"accessory",這個是和服務器端對應的,千萬不能亂寫,必定要看接口文檔,否則會上傳失敗 [paras setValue:(__bridge id)((__bridge FILE *)(voiceData)) forKey:@"accessory"]; [paras setValue:[BLLUser getPushToken] forKey:@"senderPushToken"]; [paras setValue:self.receiverPushToken forKey:@"receiverPushToken"]; [paras setObject:[Base getKey] forKey:@"ukey"]; AFHTTPRequestOperation * operation = [manager POST:kBLLUrl_Chat_Chat parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyyMMddHHmmss"; NSString *str = [formatter stringFromDate:[NSDate date]]; //fileName這裏取當前時間戳 //accessory仍是同樣和服務端對應,具體看你本身的接口文檔 //mimeType選擇@"amr/mp3/wmr",意思是告訴服務端,我上傳的文件類型是支持三種格式amr、mp3和wmr,這裏須要注意 //這裏我是上傳了一個amr格式的語音文件,那麼若是你的語音文件爲其它格式,必定要和服務端對應上,好比服務端讓你上傳wav格式的語音,那麼你拿到的是amr,怎麼辦?講個笑話,有人直接改後綴,服務端不是讓我上傳wav的嘛,直接改.wav不就能夠了嘛!真的有人這樣想這樣作了。那麼這裏告訴你,你是男的,穿了女人的衣服,你仍然是男的。即便割掉丁丁也不是女的,最多算是不男不女。解決方法就是找第三方庫,把你的amr語音轉換爲wav,而後轉爲NSData再上傳就能夠了。 NSString *fileName = [NSString stringWithFormat:@"%@.amr", str]; [formData appendPartWithFileData:voiceData name:@"accessory" fileName:fileName mimeType:@"amr/mp3/wmr"]; } success:^(AFHTTPRequestOperation *operation, NSData * responseObject) { NSLog(@"回調成功!"); NSError * error; NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error]; //json解析獲得存儲服務器返回的字典 NSLog(@"狀態==%@",dic[@"msg"]); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { //鏈接服務器失敗 NSLog(@"發送失敗"); }]; operation.responseSerializer = [AFHTTPResponseSerializer serializer]; [operation start];