2017-06-03 26 views
3

スウィフトプレイグラウンドでMS認知サービスVisions APIに画像を送信しようとしています。スウィフトプレイグラウンドで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を気にしない方が良いでしょう。

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() 
関連する問題