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

问题描述 投票:1回答:1

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

这是我得到的另一个问题的例子:

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

所以当我看一个上面的例子时,我没有得到一些要点。

1)这部分multipartFormData.append(audioRecorder?.url, withName: "iosTest.mp3")上面的“withName:”是什么?它是iphone设备中的音频文件名吗?

2)我在哪里可以设置参数和标题?

正常请求的原因我做的是这样的:

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部分的例子。这部分对我来说很困惑。 谢谢。

ios alamofire swift4
1个回答
1
投票

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

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

        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.