AnaMM
AnaMM

Reputation: 317

Convert Image to Base64 for Json Swift 3

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.

Upvotes: 0

Views: 4964

Answers (1)

shallowThought
shallowThought

Reputation: 19600

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.

Upvotes: 3

Related Questions