How to Upload Audio with Alamofire Multipart Upload

How to upload audio with Alamofire multipart upload?

Hi im using this code to upload song image and m4a file to my server .
Hope this work for you.

func call_Api_Add_PostWithImage(_ uploadImage:UIImage, _ songName:String, _ songData_:NSData,_ text:String)
{
self.slider_progress.value = 0
self.slider_progress.isHidden = false
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddhhmmss"
let dateString = dateFormatter.string(from: NSDate() as Date)
let imgName = "\(dateString)_SM_POST.png"

let profileId = AppConfig.USER_ID == parentVC.profile_id ? AppConfig.USER_ID : parentVC.profile_id
var param = API_KEYS.post_dict

param["userid"] = AppConfig.USER_ID
param["profile_id"] = profileId
param["posttype"] = "4"
param["parentpost"] = "0"
param["description"] = txt_message
param["image"] = ""
param["source"] = "1"
param["title"] = ""
param["info"] = songJsonString

Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(uploadImage, 0.5)!, withName: "audio_banner", fileName: imgName, mimeType: "image/jpeg")
multipartFormData.append(songData_ as Data, withName: "audio", fileName: songName, mimeType: "audio/m4a")
for (key, value) in param {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: API_POST_ADD_POST)
{ (result) in
switch result {
case .success(let upload, _, _):

upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
DispatchQueue.main.async {
self.slider_progress.setValue(Float(Progress.fractionCompleted), animated: true)
}

})

upload.responseJSON { response in
if let JSON = response.result.value {
print("Response : ",JSON)
if let dictJson = JSON as? NSDictionary
{
let checkResult = dictJson[successKey] as? Int ?? 0
if checkResult == 1
{
if let valueData = dictJson[resKey] as? NSDictionary
{
if let objeResponse = UserPostModel(dictionary: valueData)
{
self.parentVC.arr_userPosts.insert(objeResponse, at: 0)
DispatchQueue.main.async {
self.showSuccessPopup()
self.parentVC.tbl_profile_info.reloadData()
}
}
}
}
}
}

DispatchQueue.main.async {
self.slider_progress.value = 0
self.slider_progress.isHidden = true
}

}

case .failure(let encodingError):
print(encodingError)
DispatchQueue.main.async {
self.slider_progress.value = 0
self.slider_progress.isHidden = true
}
}

}
}

Can't upload audio file through server using Alamofire

The problem is in your Alamofire Request: You are building a JSON with the audio data in the JSON. However, you can check in Postman the HTTP code(top right/under send) that the request is Multi Part Form Data.

How to implement a multipart Alamofire:
It should be something similar to that I am not sure about appendBodyPart statements. They depend on your case

let audioData: NSData = ...//should be loaded from the file

Alamofire.Manager.upload(.PUT,
URL,
headers: headers,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: "3".dataUsingEncoding(NSUTF8StringEncoding), name: "from_account_id")
multipartFormData.appendBodyPart(data: "4".dataUsingEncoding(NSUTF8StringEncoding), name: "to_account_id")
multipartFormData.appendBodyPart(data: audioData, name: "file", fileName: "file", mimeType: "application/octet-stream")
},
encodingCompletion: { encodingResult in
switch encodingResult {

case .Success(let upload, _, _):
upload.responseJSON { response in

}

case .Failure(let encodingError):
// Error while encoding request:
}
})

Access encodingResult when uploading with Alamofire 5

Multipart encoding is fully integrated into the now-asynchronous request pipeline in Alamofire 5. That means there's no separate step to use. However, you can use the MultipartFormData type directly, just like you would in the request closure.

let data = MultipartFormData()
data.append(Data(), withName: "dataName")
try data.encode()


Related Topics



Leave a reply



Submit