如何使用Alamofire分段上传来上传音频? [英] How to upload audio with Alamofire multipart upload?

查看:223
本文介绍了如何使用Alamofire分段上传来上传音频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Alamofire 上传音频文件。我看到其他问题告诉使用Multipart请求这样做

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

以下是我从其他问题中得到的示例:

 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)什么是withName:部分是 multipartFormData.append(audioRecorder?.url,withName:iosTest.mp3)以上?它是iphone设备中的音频文件名吗?

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)我在哪里可以设置参数和标题?

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 {

所以在multipart中我应该在哪里使用特定的标题和参数?请给出一些 multipartFromData.append 部分的例子。这部分让我很困惑。
谢谢。

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.

推荐答案

您好我正在使用此代码将歌曲图像和m4a文件上传到我的服务器。
希望这对你有用。

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

        }
    }

这篇关于如何使用Alamofire分段上传来上传音频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆