如何使用Swift 3将图像发送到Emotion服务

时间:2016-11-23 07:32:28

标签: ios swift face-recognition emotion

我正在尝试将图像从UIImageView发送到Cognitive服务(Emotion API),但服务器响应有错误。

  

{“error”:{“code”:“BadArgument”,“message”:“媒体类型无效。”}}

我的代码:

let boundary = generateBoundaryString()

let url = NSURL(string: "https://api.projectoxford.ai/emotion/v1.0/recognize")!
var request =  URLRequest(url: url as URL)
request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("...my API KEY.....", forHTTPHeaderField: "Ocp-Apim-Subscription-Key")



request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let image_data =  UIImageJPEGRepresentation(cameraImageView.image!,75)

let body = NSMutableData()

let fname = "myphoto.jpg"
let mimetype = "image/jpg"

body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(using: .utf8)!)
body.append("hi\r\n".data(using: .utf8)!)
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".data(using: .utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: .utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: .utf8)!)

body.append("--\(boundary)--\r\n".data(using: .utf8)!)        
request.httpBody = body as Data
request.httpMethod = "POST"  
let task = URLSession.shared.dataTask(with: request){ data, response, error in
    if error != nil{
        print("Error -> \(error)")
        return
    }
    do {
        print("json-DONE")


        if let data = data, let jsonString = String(data: data, encoding: String.Encoding.utf8) , error == nil {
            print(jsonString)
            print("json-DONE1")
        } else {
            print("error=\(error!.localizedDescription)")
        }




    } catch {
        print(error)
    }
}

task.resume()

提前谢谢!!

0 个答案:

没有答案