Reputation: 1425
I am trying to send a post request to and api that contains a list of "items" that can be either an image or text.
However, I keep getting an error (listed in Title)
Here is the code turning my objects into JSON
var json = [String: Any]()
var jsonItems = [Any]()
for i in 0...(items.count - 1){
var it = [String: Any]()
if let imageData = items[i].image?.jpgData(){
it["image"] = imageData
}
if let text = items[i].text{
it["text"] = text
}
if i == 0 {
it["is_profile"] = true
it["face_detected"] = faceDetected
}
jsonItems.append(it)
}
json["items"] = jsonItems
Is there any reason why this would not be formatted correctly?
EDIT:
The jpgData function
func jpgData() -> Data? {
return UIImageJPEGRepresentation(self, 0.8)
}
Example code that causes crash:
extension Dictionary {
var json: String {
let invalidJson = "Not a valid JSON"
do {
let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson
} catch {
return invalidJson
}
}
}
In addition to my sample code, passing the created dict as the param for Alamofire requests, URLSession requests, etc all cause a crash with the error from the title
EDIT: Solution
Image data did need to be encoded. Feels so obvious in hindsight. Base64 encoding worked for printing out the structure like in my extension, but for network requests I ended up using Alamofire's MultipartFormData class (a custom wrapper around it) and appended as an application/octet-stream
for the mimetype. Wish I could use a facepalm emoji here. I accepted one of the two answers that talked about encoding that actually had sample code.
Upvotes: 1
Views: 292
Reputation: 1507
After converting to JPEG Data try encoding to base64
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
Check this answer for more info Convert between UIImage and Base64 string
Upvotes: 1
Reputation: 33967
A Data cannot be put into JSON. The Data object will have to be encoded. Probably using base64 encoding.
Upvotes: 0