Search code examples
iosswiftpostalamofire

Post base64String of image with other parameters to server swift


Here I have an image which I am converting in base64String (†he resulted base64String is too large) and try to post on server with some other parameters but in return I am getting failure. I am having an done action button on tap it started converting and post to server. I used Alamofire for http request. Below is my code which I used but not getting result.

@IBAction func doneBtn(_ sender: Any) {

    if (itemNameTF.text?.characters.count)! > 0 && (itemPriceTF.text?.characters.count)! > 0 && (itemUnits.text?.characters.count)! > 0 {

    let productName = "\(itemNameTF.text!)_\(itemUnits.text!)"

        let productPrice = itemPriceTF.text!

        let productImage:UIImage = itemImage.image!
        if let dataImage = UIImageJPEGRepresentation(productImage, 0.5)?.base64EncodedString() {

            let url = "someURl"
            let parameter = ["product_name": productName, "product_price": productPrice, "product_img": "\(dataImage)"]

            headers = ["Content-Type": "application/json","Authorization" : "Token \(token!)"]
            Alamofire.request(url, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
                print(response.request)
                print(response.response)
                print(response.result)
                print(response.result.value)
            }
        }
    }
} 

In result it gives me an response of

enter image description here

Please help me if anyone could find problem. Thank You!


Solution

  • Just add this line into your code:

    let fullBase64String = "data:image/png;base64,\(dataImage))"
    

    and then add "fullBase64String"

    let parameter = ["product_name": productName,"product_price":productPrice,product_img": "\(fullBase64String)"]