Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

ios - How to upload audio with Alamofire multipart upload?

I want to upload and audio file with using Alamofire. I see other questions which are telling to use Multipart request to do that

Here is the example i got form other question :

 Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(audioRecorder?.url, withName: "iosTest.mp3")
                             //**this "withName:" is it the name of the file? 
    },
    to: "https://yourLinkGoesHere",
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

So when i look at an example above and i did not get a few points to understand.

1) what is "withName:" in this part multipartFormData.append(audioRecorder?.url, withName: "iosTest.mp3") above? Is it an audio file name in iphone device?

2) Where can i set parameters and headers?

Cause in normal request what i do is like this :

let headers : HTTPHeaders = ["Authorization" : apiKey]
 let params : [String : Any] = ["my_param" : myParams]

  Alamofire.request(My_URL!, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON {
            response in
            switch response.result {

So in multipart where should i specific headers and params? Please give some example for multipartFromData.append part.This part is quite confusing for me.
Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
                }
            }

        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...