swiftalamofirealamofireimage

Send image with certain parameters?


I have no problem sending plain text.

For example, I have this request:

func buyWholeSaler(url : String, token:String, manager:String, fio:String,phone:String, sender:String, carrier:String, document:String,shipping_id:String,pay_type:String, shipping_pay:String, amount_nalogi:String, shipping_return:String,money_recipient :String,comment:String, completion: @escaping (JSON)-> Void) {
        let headers: HTTPHeaders = [
            "Authorization": "Bearer \(token)",
            "Accept": "application/json"
        ]

        let parameters: Parameters = [
            "shipping_id" : shipping_id,
            "pay_type": pay_type,
            "manager" : manager,
            "fio" : fio,
            "phone" : phone,
            "sender" : sender,
            "carrier" : carrier,
            "document" : document,
            "shipping_pay": shipping_pay,
            "amount_nalogi": amount_nalogi,
            "shipping_return" :shipping_return,
            "money_recipient" : money_recipient,
            "comment" : comment
        ]
        AF.request(url,method: .post, parameters: parameters, headers:headers).responseJSON { response in
            switch response.result {
            case .success(let value):
                let json = JSON(value)
                completion(json)
            case .failure(let error):
                print(error)
            }
        }
    }

But how can I send a picture with these parameters?

I have 2 images

var image1 = UIImage()
var image2 = UIImage()

How can I rewrite the request in order to send it correctly? For example:

let parameters: Parameters = [
            "shipping_id" : shipping_id,
            "pay_type": pay_type,
            ...
            "ur_file_pdv": image1,
            "ur_file_er": image1
        ]

I found this request but I cannot understand how it works:

AF.upload(multipartFormData: { multiPart in
                        for p in parameters {
                            multiPart.append("\(p.value)".data(using: String.Encoding.utf8)!, withName: p.key)
                        }
                        multiPart.append(imageVityagPdv.jpegData(compressionQuality: 0.4)!, withName: "ur_file_pdv", fileName: "ur_file_pdv.jpg", mimeType: "image/jpg")
                        multiPart.append(imageVityag.jpegData(compressionQuality: 0.4)!, withName: "ur_file_er", fileName: "ur_file_er.jpg", mimeType: "image/jpg")
                    }, to: url, method: .post, headers: headers) .uploadProgress(queue: .main, closure: { progress in
                        print("Upload Progress: \(progress.fractionCompleted)")
                    }).responseJSON(completionHandler: { data in
                        print("upload finished: \(data)")
                        let success = json["success"].stringValue
                    }).response { (response) in
                        switch response.result {
                        case .success(let resut):
                            print("upload success result: \(resut!)")
 case .failure(let err):
                            print("upload err: \(err)")
                        }
                    }

It seems to be uploading something to the server but the order does not happen


Solution

  • You can't add "Data" as a Parameter, especially since a "request" is made to retrieve data from a server and should be pretty small, just giving the server info on what you actually want to receive from it (in textual form). To upload something, you use a POST request which you can do in Alamofire using AF.upload like shown below.

    What do you mean by "order does not happen"? Maybe you have some server code so we can see what the issue is? Could be that it wants the parameters as GET, in that case you could add them directly to the URL.

    func buyWholeSaler(url : String, token: String, manager: String,
        fio: String, phone: String, sender: String, carrier: String,
        document: String, shipping_id: String, pay_type: String,
        shipping_pay: String, amount_nalogi: String,
        shipping_return: String, money_recipient: String, comment:String,
        completion: @escaping (JSON) -> Void) {
    
        let headers: HTTPHeaders = [
            "Authorization": "Bearer \(token)",
            "Accept": "application/json"
        ]
    
        let parameters: Parameters = [
            "shipping_id" : shipping_id,
            "pay_type": pay_type,
            "manager" : manager,
            "fio" : fio,
            "phone" : phone,
            "sender" : sender,
            "carrier" : carrier,
            "document" : document,
            "shipping_pay": shipping_pay,
            "amount_nalogi": amount_nalogi,
            "shipping_return" :shipping_return,
            "money_recipient" : money_recipient,
            "comment" : comment
        ]
    
        AF.upload(multipartFormData: { (multipartFormData) in
            parameters.forEach({ multipartFormData.append("\(p.value)".data(using: .utf8)!, withName: p.key) })
            multipartFormData.append(image1.jpegData(compressionQuality: 0.4)!,
                withName: "ur_file_pdv", fileName: "ur_file_pdv.jpg", mimeType: "image/jpg")
            multipartFormData.append(image2.jpegData(compressionQuality: 0.4)!,
                withName: "ur_file_er", fileName: "ur_file_er.jpg", mimeType: "image/jpg")
        },
        to: url, method: .post, headers : headers).responseJSON { (response) in
            switch response.result {
            case .success(let value): completion(JSON(value))
            case .failure(let error): print(error)
            }
        }
    }