0

i am trying to send an image to an api using alamofire heres what i got:

var uploadedProfileImage: UIImage = UIImage()

let body: Parameters = [

          "profilePic": uploadedProfileImage,
          "name": "John Doe"
                  ]
Alamofire.request(BASE_URL",method: .post,parameters: body,encoding: JSONEncoding.default).responseData { response in
                                                debugPrint("All Response Info: \(response)")

                                                if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
                                                    print("Data: \(utf8Text)")
                                                }
                                            }

so this is the code i am using uploadProfileImage has an image that the user picked from the library and my api receives a json body parameter in which it has profilePic which is off type file when i run this its giving me an error saying 'Invalid type in JSON write (UIImage)'.theres is also a terminating with uncaught exception of type NSException error. what am i doing wrong and how to fix it?

Jhon
  • 99
  • 3
  • 15

1 Answers1

0

You can't upload image with

"profilePic": uploadedProfileImage

as it's used for types that are encode-able such as strings , you need

upload image to server using Alamofire

func uploadImageAndData(_ url:String,parameters1:Parameters,headers1:HTTPHeaders,images:[UIImage]){


    Alamofire.upload(multipartFormData: { multipartFormData in
        // import image to request
        var i=0
        for imageData in images {
            //  multipartFormData.append(self.resizeImage(image: imageData, targetSize: CGSize(width: 400, height:
            multipartFormData.append(imageData.pngData()!, withName: "image", fileName: "image"+".jpeg", mimeType: "image/jpeg")
            i += 1


        }
        for (key, value) in parameters1 {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    } ,to: url,method:.post,
       headers:[:],

       encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (Progress) in
                print("Upload Progress: \(Progress.fractionCompleted)")
                //SwiftSpinner.show(progress: Progress.fractionCompleted*100, title: "تحميل")
            })
            upload.responseJSON { response in

                switch response.response?.statusCode {

                case 200 :


                    break

                case 400 :


                    break

                case 401 :


                    break


                case 302 :


                    break
                case 500 :


                    break

                default: break


                }

            }
            return
        case .failure(let encodingError):

        }

    })
}

    var head = [String:Any]()
    head["Accept"]="application/json"
    head["Authorization"] = "Bearer \(tokenIfExists)"
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • is there a possible solution? – Jhon Aug 15 '19 at 12:30
  • ok i checked it out Thanks, i also have other variables in the parameters variables like names and everything can i also send those datas together using the upload method? – Jhon Aug 15 '19 at 12:36
  • if you can maybe send a code snippet using my scenario i am new to swift – Jhon Aug 15 '19 at 12:36
  • what kind of should i provide for the HttpHeader parameters? – Jhon Aug 15 '19 at 14:20
  • Thank you for the support it really helped a lot, but i have a related question i have posted it here https://stackoverflow.com/questions/57521590/alamofire-sending-a-request-to-an-api-nsinvalidargumentexception i would really appreciate it if you can check it out. – Jhon Aug 16 '19 at 09:05