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?

8
  • convert image to base64String and pass String to server not the data Commented Feb 15, 2018 at 5:14
  • request.httpBody is of data type and you are trying to assign a string to it. Commented Feb 15, 2018 at 5:16
  • Please check out this answer. <stackoverflow.com/questions/39441508/…> Commented Feb 15, 2018 at 5:17
  • here i am converting the image into string . please check image_data?.base64EncodedString() Commented Feb 15, 2018 at 5:17
  • What does the api expect? is it expecting data or string? Commented Feb 15, 2018 at 5:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

it will go as data or string?
since you're needing data, you should be able to submit "imgData"
But what if the API doesn't require any top-level keys?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.