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.