모바일/iOS

Swift2 - Using faceAPI and sending binary data to server

늘근이 2016. 6. 6. 22:58

핵심은 쓰잘데기 없는거 지우고 마이크로소프트  faceAPI 를 이용할시 다음과 같이 이용한다.


func imageUploadRaw(image:UIImage){

    

    let request = NSMutableURLRequest(URL: NSURL(string: "https://api.projectoxford.ai/face/v1.0/detect?entities=true&returnFaceId=true&returnFaceLandmarks=true&returnFaceAttributes=age")!)

    request.HTTPMethod = "POST"

    

    let imageData :NSData = UIImagePNGRepresentation(image)!


    

    let body = NSMutableData();


    body.appendData(imageData)


    request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")

    request.setValue("your key",forHTTPHeaderField: "Ocp-Apim-Subscription-Key")

    

    request.HTTPBody = body

    

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

        data, response, error in

        

        if error != nil {

            print("error=\(error)")

            return

        }

        

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

        print("responseString = \(responseString!)")

    }

    task.resume()

    

}


바로   body.appendData(imageData)를 넣는것이다. NSData 자체가 바이너리이며, 이를 굳이 8바이트 행렬로 변환하기 위한 생쇼를 하지 않아도 된다. 생쇼를 하기 시작하면 다음과같이 에러를 보게 된다

이글을 보는 세계각지의 삽질러들한테도 영어로 전한다.
스위프트가 아주 레퍼런스가 없어서 고생이다.

Decoding error, image format unsupported.


When using Microsoft FaceAPI and If this message is shown, Just follow the code I wrote there.

Microsoft mentioned that you should put the local binary data to body, but they don't let us know how to put it. In case of Swift, binary data means NSData. NSData is all you need to put into body.

Don't need to put any unnecessary request header or body other than mentioned above.

Just put converted NSData, which is derived from UIImagePNGRepresentation (OR JPEG), into body and it will work.

Yes Swift Sucks


'모바일 > iOS' 카테고리의 다른 글

[링크] Swift - SQLite  (0) 2016.06.07
Swift2 - NSData to ByteArray (UInt8)  (0) 2016.06.06
Swift2 - Multipart Data send  (0) 2016.06.06
Swift2 - Failed to obtain sandbox extension for  (0) 2016.06.06
Swift2- Reflection 사용법?  (0) 2016.06.06