2017-06-03 72 views
3

我尝试将图像发送到Swift Playground中的MS Cognitive Services Visions API在Swift Playground中通过POST发送图像

我得到的响应的消息是:

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

我怀疑我是不是正确发送图像。有任何想法吗?

回答

2

最好不要打扰多部分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()