如何使用Alamofire Swift将选定的图像从ImagePickerController发送到服务器

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

希望大家身体健康。

我正在使用iOS应用,用户从手机库中选择图像或从相机中捕获图像。我为此使用UIImagePickerController。该照片(从图库中选择或通过相机捕获)发送到服务器。

我有传递两个参数的API,一个是rigerID,另一个是从UIImagePickerController中选择的图片。

这是我的更改配置文件按钮代码:


    @IBAction func changeProfilePicAct(_ sender: UIButton) {



        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: { _ in
            self.openCamera()
        }))

        alert.addAction(UIAlertAction(title: "Choose Photo", style: .default, handler: { _ in
            self.openGallary()
        }))

        alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))

        //If you want work actionsheet on ipad then you have to use popoverPresentationController to present the actionsheet, otherwise app will crash in iPad
        switch UIDevice.current.userInterfaceIdiom {
        case .pad:
            alert.popoverPresentationController?.sourceView = sender
            alert.popoverPresentationController?.sourceRect = sender.bounds
            alert.popoverPresentationController?.permittedArrowDirections = .up
        default:
            break
        }

        self.present(alert, animated: true, completion: nil)
    }

func openCamera(){
        if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera)){
            imagePicker.sourceType = UIImagePickerController.SourceType.camera
            imagePicker.allowsEditing = true
            imagePicker.delegate = self
            self.present(imagePicker, animated: true, completion: nil)
        }
        else{
            let alert  = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
func openGallary(){
        imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
        imagePicker.allowsEditing = true
        imagePicker.delegate = self

        //uploadImgRiderAPI()
        self.present(imagePicker, animated: true, completion: nil)
    }





这是API调用函数


    func uploadImgRiderAPI(userImage : UIImage?,withCompletionHandler:@escaping (_ result: Any) -> Void){

        print("I am in uploadImgRiderAPI")

        let parameters : [String : String] = ["image": "alkaram.png", "riderId" : "5ed4eecfe3ec0c6b7c8e4990"]

        guard let url = URL(string: "\(Constents.baseURL)/rider/uploadImage") else {
            print("Invalid URL")
            return
        }
                    AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON{ response in

                        print("Response is : \(response)")


                        switch response.result {
                        case .success:
                            if let result = response.data {
                                do {

                                    let jsonData = try JSONEncoder().encode(parameters)
                                    let jsonString = String(data: jsonData, encoding: .utf8)


                                    let url = URL(string: self.retrivedRiderProfileImg!)
                                    print("Complete URL is :-> \(url)")

                                    let placeholderImage = UIImage(named: "referral_icon")!
                                    self.profilePicOut.af_setImage(withURL: url!, placeholderImage: placeholderImage)

                                    print("JSON String : " + jsonString!)
                                    print("And Responce is : \(response)")


                                } catch {
                                    print(error)

                                }
                            }

                        case .failure(let error):
                            print(error)

                        }
                    }
   }


邮递员:

This is the parameters Postman view谢谢🙂

ios swift alamofire
1个回答
0
投票

您可能需要使用多部分表单数据而不是JSON来上传图像数据

func uploadImgRiderAPI(userImage : UIImage?,withCompletionHandler:@escaping (_ result: Any) -> Void){

    print("I am in uploadImgRiderAPI")
    let imgData = UIImageJPEGRepresentation(image!, 0.2)! // 0.2 is the compress rate
    let parameters : [String : String] = ["image": "alkaram.png", "riderId" : "5ed4eecfe3ec0c6b7c8e4990"]

    guard let url = URL(string: "\(Constents.baseURL)/rider/uploadImage") else {
        print("Invalid URL")
        return
    }

    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "image",fileName: "alkaram.png", mimeType: "image/jpg")
        for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            } //Optional for extra parameters
    }, to:url) { (result) in
        switch result {
        case .success(let upload, _, _):

            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                 print(response.result.value)  
                 if let result = response.data {
                            do {

                                let jsonData = try JSONEncoder().encode(parameters)
                                let jsonString = String(data: jsonData, encoding: .utf8)


                                let url = URL(string: self.retrivedRiderProfileImg!)
                                print("Complete URL is :-> \(url)")

                                let placeholderImage = UIImage(named: "referral_icon")!
                                self.profilePicOut.af_setImage(withURL: url!, placeholderImage: placeholderImage)

                                print("JSON String : " + jsonString!)
                                print("And Responce is : \(response)")


                            } catch {
                                print(error)

                            }
                        }
            }

        case .failure(let encodingError):
            print(encodingError)  
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.