首页 > 代码库 > Alamofire +ObjectMapper模型: 上传音频。
Alamofire +ObjectMapper模型: 上传音频。
import Foundation
import Alamofire
//上传音频 ,multipartFormData 上传。key = audio
extension HttpManager {
/**
音频文件
- parameter audioData: 音频 Data
- parameter success: 成功回调 audio model
- parameter failure: 失败
*/
class func uploadAudio(
_ audioData: Data,
recordTime: String,
success:@escaping (_ audioModel: UploadAudioModel) ->Void,
failure:@escaping (Void) ->Void)
{
let parameters = [
"access_token": UserInstance.accessToken,
"record_time": recordTime
]
/*
这里需要填写上传音频的 API
*/
let uploadAudioURLString = ""
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(audioData, withName: "audio", fileName: "file", mimeType: "audio/AMR")
for (key, value) in parameters {
multipartFormData.append(value!.data(using: String.Encoding.utf8)!, withName: key)
}
},
to: uploadAudioURLString,
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
//XCGLogger,TSLogger.swift
log.info("response:\(response)")
switch response.result {
case .success(let data):
/*
根据 JSON 返回格式,做好 UploadAudioModel 的 key->value 映射, 这里只是个例子
*/
let model: UploadAudioModel = TSMapper<UploadAudioModel>().map(JSONObject: data)!
success(model)
case .failure( _):
failure()
}
}
case .failure(let encodingError):
debugPrint(encodingError)
}
})
}
}
// 上传音频接口返回的图片 Model
//class UploadAudioModel : TSModelProtocol {
// var audioId : String?
// var duration : Int?
// var audioURL : String?
// var fileSize : Int?
// var keyHash : String?
// var recordTime : String?
//
// required init?(map: Map) {
//
// }
//
// func mapping(map: Map) {
// audioId <- map["audio_id"]
// audioURL <- map["audio_url"]
// duration <- map["duration"]
// keyHash <- map["key_hash"]
// fileSize <- map["file_size"]
// recordTime <- map["recordTime"]
// }
//}
//使用的地方
/**
* 异步上传音频文件, 然后上传成功后,把 model 值改掉
* 因为还没有上传的 API,所以这个函数会返回错误 T.T
HttpManager.uploadAudio(uploadAmrData, recordTime: String(recordTime), success: {model in
audioModel.keyHash = model.keyHash
audioModel.audioURL = model.audioURL
audioModel.duration = recordTime
}, failure: {
})
}
*/
Alamofire +ObjectMapper模型: 上传音频。