0

I need to convert an UIImage to base64 for send it on a JSON. My problem is the conversion. My code:

//Proof #1
let base64String = imageData?.base64EncodedData(options: .endLineWithLineFeed)
//Proof #2 
let base64String = imageData?.base64EncodedString(options: .endLineWithLineFeed)

let dataJson = ["patient_image": ["title": titleInfo, "description": descriptionInfo, "patient_id": globalID, "images_attributes": ["file": base64String]]]

    let url = NSURL(string: "MY_URL")

    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "POST" //set http method as POST

    request.httpBody = try! JSONSerialization.data(withJSONObject: dataJson, options: .prettyPrinted)

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

I tried both ways Swift 3 provides for convert an image to base64, but with both i get the same error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

Can somebody help me? I really appreciate your help.

1 Answer 1

3

Remove the options:

let base64String = imageData.base64EncodedString()

Complete code:

/*
let imageData = Data()
let titleInfo = "test"
let descriptionInfo = "test"
let globalID = "test"
*/

let base64String = imageData.base64EncodedString()

let dataJson = ["patient_image": ["title": titleInfo, "description": descriptionInfo, "patient_id": globalID, "images_attributes": ["file": base64String]]]

let url = NSURL(string: "MY_URL")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST

request.httpBody = try! JSONSerialization.data(withJSONObject: dataJson, options: .prettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

Also (independent of your issue) the key name images_attributes sounds like it expects an array.

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

1 Comment

let base64String = imageData.base64EncodedString() Cool, it helps me a lot. But I'd like to know why and what's the difference if we use option?

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.