0

Currently I use:

func post(_ url: URL, parameters: [String: Any]?, image: UIImage?, headers: [String: String]?, success: @escaping SuccessHandler, failure: @escaping ErrorHandler) {
    manager.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON { [weak self] response in
        //do something with a response
    }
}

How can I append image to the request?

halfer
  • 19,824
  • 17
  • 99
  • 186
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

2 Answers2

0

Here is my answer

 Alamofire.upload(multipartFormData: { multipartFormData in

            //Single image to pass here
            if image != nil{
                if let imageData = UIImageJPEGRepresentation(image!, 0.8) {
                    multipartFormData.append(imageData, withName: "Your key here", fileName: "\(UUID().uuidString).jpeg", mimeType: "image/jpeg")
                }
            }

            //Here array of UIImages
            if images.count != 0{
                for img in images{
                    if let imageData = UIImageJPEGRepresentation(img, 0.8) {
                        multipartFormData.append(imageData, withName: "Your key here", fileName: "\(UUID().uuidString).jpeg", mimeType: "image/jpeg")
                    }
                }
            }


            //params are your other post parameters
            if let parm = params{
                for (key, value) in parm {
                    multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
            }


         }, to: "Your url here" , method: .post, headers: headers,
            encodingCompletion: { encodingResult in


                switch encodingResult {
                case .success(let upload, _, _):
                    //Success response
                case .failure(let encodingError):
                    //Failure response

                }
         })
Jitendra Modi
  • 2,344
  • 12
  • 34
0

You should consider using upload method :

manager.upload(multipartFormData: { (multipartFormData) in

        for (key,value) in data{
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
        }

        if let file = self.attachedFile{
            if let f = file.getFile()
            {
                multipartFormData.append(f, withName: "some_name", fileName: "attachement.pdf", mimeType: "application/pdf")
            }
        }

    }, to:"Some URL",
       method: .post,
       encodingCompletion: { encodingResult in 


            switch encodingResult {
            case .success(let upload, _, _):
                //Success response
            case .failure(let encodingError):
                //Failure response

            }
     })
Pradeep Kumar Kushwaha
  • 2,231
  • 3
  • 23
  • 34