0

Here I have to post base64encoded image to server. Below is my code which I am using:

 func post_request_image(api:String){

    if (imageview.image == nil)
    {
        return
    }
     let image_data = UIImageJPEGRepresentation(imageview.image!, 1.0)

    if(image_data == nil)
    {
        return
    }

    loader.showLoadingAlert(view: self.view, title: "")
    var web_apis_3 = api
    // print(web_apis_3)
    var request = URLRequest(url: URL(string: web_apis_3)!)
     request.httpMethod = "POST"
     do {
        request.httpBody = 
         image_data?.base64EncodedString()

    } catch let error {
        print(error.localizedDescription)
    }
    // let content = String(data: json!, encoding: 
         String.Encoding.utf8)

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")

        }

}

But it is giving me this error:

cannot assign value of type String to type Data

How can I resolve this?

asif saifi
  • 166
  • 1
  • 11

1 Answers1

1

if the server expects a string:

let image = UIImage(named: "sample")
guard let imgData = UIImagePNGRepresentation(image) else { return }
let base64String = imgData.base64EncodedString(options: .lineLength64Characters)

then submit base64String to the server in whatever way is needed.

for me I needed to submit:

let parameters: [String: String] = [
    "image": base64String
]

since youre needing data, you should be able to submit imgData

Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
valosip
  • 3,167
  • 1
  • 14
  • 26