小编NMA*_*427的帖子

在Swift中的cURL等价 - iOS

我已经尝试了不同的东西来创建这个cURL请求的快速等价物,但我无法让它工作.

curl -X POST -F "file=@/Users/nicolas/sample.png" -F "mode=document_photo" https://api.idolondemand.com/1/api/sync/ocrdocument/v1 -F "apikey=xxx-xxx-xxx-xxx-xxx"
Run Code Online (Sandbox Code Playgroud)

相应的代码发布在下面.

func getText (image: UIImage){

    let apiKey = "xxx-xxx-xxx-xxx-xxx"

    let request = NSMutableURLRequest(URL: NSURL(string: "https://api.idolondemand.com/1/api/sync/ocrdocument/v1")!)
    request.HTTPMethod = "POST"
    request.addValue(apiKey, forHTTPHeaderField: "apikey")
    request.addValue("document_photo", forHTTPHeaderField: "mode")
    request.HTTPBody = UIImageJPEGRepresentation(image, 1)

    let task = NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: UIImageJPEGRepresentation(image, 1), completionHandler: {data, response, error -> Void in


        if let _ = data {
            var error:NSError? = nil
            do {
                let jsonObject : AnyObject = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
                let json = JSON(jsonObject)
                if let …
Run Code Online (Sandbox Code Playgroud)

curl ios swift

5
推荐指数
1
解决办法
2384
查看次数

CURL with Alamofire - Swift - multipart/form-data

首先,我很抱歉,如果这个问题是愚蠢的,但我对这个东西很新.我尝试过用Alamofire创建快速等效的cURL请求,但我不知道如何将图像作为multipart/form-data发送到API.

curl -X POST -F "file=@/Users/nicolas/sample.png" -F "mode=document_photo" https://api.idolondemand.com/1/api/sync/ocrdocument/v1 -F "apikey=xxx-xxx-xxx-xxx-xxx"
Run Code Online (Sandbox Code Playgroud)

我认为当前的代码对于这种类型的请求是非常错误的,但我仍然会为你发布它:

func getOCR(image: UIImage) {

    let url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1"
    let apiKey = "xxx-xxx-xxx-xxx-xxx"
    let imageData = UIImagePNGRepresentation(image)

    Alamofire.request(.POST, url, parameters: ["apikey": apiKey, "file": imageData!]).responseJSON() {
        _,_,JSON in
        print(JSON)
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止它对我有用的唯一方法是使用URL,但是因为我尝试将图像发送到用户用相机拍摄的服务器,所以我只能发送图像文件.

网址代码:

func test(url: NSURL) {

    let url = "https://api.idolondemand.com/1/api/sync/ocrdocument/v1"
    let apiKey = "xxx-xxx-xxx-xxx-xxx"

    Alamofire.request(.POST, url, parameters: ["apikey": apiKey, "url": url]).responseJSON() {
        _,JSON,_ in
        print(JSON)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我收到回复,我会很高兴,因为这让我发疯.

PS.我正在使用swift 2.0

curl multipartform-data swift alamofire swift2

3
推荐指数
1
解决办法
3395
查看次数

标签 统计

curl ×2

swift ×2

alamofire ×1

ios ×1

multipartform-data ×1

swift2 ×1