我尝试将图像发送到Swift游乐场中的MS认知服务视觉API。
我收到的消息是:
Response ["requestId": …, "code": InternalServerError, "message": Internal server error.]
这是我使用的代码
let image = #imageLiteral(resourceName: "paper.jpg")
let imageData = UIImageJPEGRepresentation(image, 1)!
let endpoint = ("https://westeurope.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Description,Categories,Tags&subscription-key=(subscriptionKey)")
let requestURL = URL(string: endpoint)!
let session = URLSession(configuration: URLSessionConfiguration.default)
var request:URLRequest = URLRequest(url: requestURL)
request.httpMethod = "POST"
// Image
let boundary = UUID().uuidString
request.addValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
var body = NSMutableData()
body.append("rn--(boundary)rn".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name="file"; filename="image.jpg"\rn".data(using: .utf8)!)
body.append("Content-Type: application/octet-streamrnrn".data(using: .utf8)!)
body.append(imageData)
body.append("rn--(boundary)rn".data(using: .utf8)!)
request.httpBody = body as Data
let task = session.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print("Response (json)")
} catch let error as Error {
print("Error (error)")
}
}
task.resume()
我怀疑我没有正确发送图像。有什么想法吗?
最好不要打扰多部分的哑剧,尤其是当您考虑其他认知服务属性(即面对和情感(不支持它时。
let subscriptionKey = "YOUR-KEY"
let image = #imageLiteral(resourceName:"monkey.jpg")
let imageData = UIImageJPEGRepresentation(image, 1.0)!
let endpoint = ("https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Description,Categories,Tags")
let requestURL = URL(string: endpoint)!
let session = URLSession(configuration: URLSessionConfiguration.default)
var request:URLRequest = URLRequest(url: requestURL)
request.httpMethod = "POST"
request.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.addValue(subscriptionKey, forHTTPHeaderField: "Ocp-Apim-Subscription-Key")
request.httpBody = imageData
var semaphore = DispatchSemaphore.init(value: 0);
let task = session.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
print("Response (json)")
} catch let error as Error {
print("Error (error)")
}
semaphore.signal()
}
task.resume()
semaphore.wait()