how to send selected Image from ImagePikerController to server using Alamofire Swift

Hopefully, All of you'll be fine with great health.

I'm working on an iOS App where the user select image from phone gallery or Capture from Camera. I'm using UIImagePickerController for that purpose. That Pic (Choose from gallery or Capture through Camera) send to server.

I have API that pass two parameters, one is rigerID and other one is picture that selected from UIImagePickerController.

Here is my Change Profile Button Code:


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





And here is API Call Function


    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)

                        }
                    }
   }


Postman:

This is the parameters Postman view Thanks 🙂

1 answer

  • answered 2020-06-02 10:19 KTang

    You may need to use multipart form data instead of JSON to upload image data

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