在Swift游乐场通过POST发送图像

时间:2017-06-03 11:22:00

标签: json swift swift-playground microsoft-cognitive

我尝试将图像发送到Swift Playground中的MS Cognitive Services Visions 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("\r\n--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\\r\n".data(using: .utf8)!)
body.append("Content-Type: application/octet-stream\r\n\r\n".data(using: .utf8)!)
body.append(imageData)
body.append("\r\n--\(boundary)\r\n".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()

我怀疑我没有正确发送图像。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

最好不要使用多部分MIME,特别是考虑到其他认知服务属性(即Face和Emotion)不支持它时。

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()