简体   繁体   English

如何使用 Alamofire 分段上传上传音频?

[英]How to upload audio with Alamofire multipart upload?

I want to upload and audio file with using Alamofire .我想使用Alamofire上传和音频文件。 I see other questions which are telling to use Multipart request to do that我看到其他问题告诉我们使用 Multipart 请求来做到这一点

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? 1) 上面multipartFormData.append(audioRecorder?.url, withName: "iosTest.mp3")这部分中的“withName:”是什么? Is it an audio file name in iphone device?它是iphone设备中的音频文件名吗?

2) Where can i set parameters and headers? 2) 我在哪里可以设置参数和标题?

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.请举一些multipartFromData.append部分的例子。这部分对我来说很混乱。
Thanks.谢谢。

Hi im using this code to upload song image and m4a file to my server .嗨,我使用此代码将歌曲图像和 m4a 文件上传到我的服务器。 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
                }
            }

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM