简体   繁体   中英

Sending an image via POST in a Swift Playground

I try to send an image to the MS Cognitive Services Visions API in a Swift Playground.

The message I get as response is:

Response ["requestId": …, "code": InternalServerError, "message": Internal server error.]

Here is the code I use

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

I suspect I am not sending the image correctly. Any ideas?

It's probably best to not bother with a multi-part MIME, especially when you consider that the other Cognitive Service properties (namely Face and Emotion) don't support it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM