I have been trying to send an image using Swift 4 and iOS 11 using the CloudSight API. I am currently converting the image to a base64 encoded string and sending the data as JSON to the CloudSight server, but I am always getting a null response. The CloudSight staff recommended to me that I don’t use base64 and that I should be using a multipart/form-data request. Any help would be appreciated as the CloudSight documentation does not fully cover how to use images that are stored in variables such as my case, so I am unsure about the keys I should be using when creating my POST parameters, and how to structure a multipart request in this case. The imageData variable is converting a UIImage that is a photo taken by an iPhone 7, so I’m guessing image size might be a problem. I would be happy to answer any other questions, and thanks again for the help! I have installed the CloudSight Pod and imported it as well, not sure if that will make a difference.
This is my current code that is having the issue (I replaced API KEY with my actual key):
let imageData:NSData = UIImagePNGRepresentation(image)! as NSData
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
let rawimage = UIImageJPEGRepresentation(image, 0.7)!
let url2 = URL(string: )!"https://api.cloudsight.ai/v1/images"
var request = URLRequest(url: url2)
request.httpMethod = "POST"
request.addValue("application/json""Content-Type", forHTTPHeaderField: )
request.addValue("CloudSight API KEY", forHTTPHeaderField: "Authorization")
request.httpBody = \strBase64."{\n \"image\": \"()\",\n \"locale\": \"us_en\" \n}"data(using: .utf8)
let task = URLSessionshareddataTask..(with: request) { data, response, error in
ifletlet response = response, data = data {
let res = JSON(data)
print("CLOUD RESPONSE ()"\response)
print("CLOUD DATA ()"\res)
}
else {
printString((describing: error))
}
}
task.resume()
This is the response I am getting from the server:
CL RESPONSE <NSHTTPURLResponse: 0x1c4238ea0> { URL: https://api.cloudsight.ai/v1/images } { status code: 400, headers {
"Content-Length" = 0;
"Content-Type" = "text/html; charset=utf-8";
Date = "Sun, 08 Oct 2017 05:26:32 GMT";
Server = "nginx/1.8.1";
"x-request-id" = "8494da71-f589-439f-b67e-c709f2c1cd7b";
"x-runtime" = "1.448816";
} }
CL DATA null
Printing data without converting to JSON also prints "nil".
Thanks again!