【问题标题】:Alamofire strange JSON prefix - Swift 2.0Alamofire 奇怪的 JSON 前缀 - Swift 2.0
【发布时间】:2015-08-05 17:46:06
【问题描述】:

我试图从 API 获取 JSON 文件,但 Alamofire(分支:Swift 2.0)返回的文件带有一个奇怪的前缀(Alamofire.Result.Success)。如果这是一个愚蠢的问题,我很抱歉,但我是 alamofire 的新手。我怎样才能得到一个可以与 SwiftyJSON 一起使用的 NORMAL 文件。

我的代码:

func getText (image: UIImage){

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

    Alamofire.upload(
        .POST,
        url,
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(
                data: apiKey.dataUsingEncoding(NSUTF8StringEncoding)!,
                name: "apikey"
            )
            multipartFormData.appendBodyPart(
                data: mode.dataUsingEncoding(NSUTF8StringEncoding)!,
                name: "mode"
            )
            multipartFormData.appendBodyPart(data: imageData!, name: "file",fileName: "image.png", mimeType: "image/png")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON  { _, _, json in

                        print(JSON)

                }
            case .Failure(let encodingError):
                print(encodingError)
            }
        }
    )
}

打印输出(JSON):

Alamofire.Result<Swift.AnyObject>.Success([text_block: (
        {
        height = 127;
        left = 0;
        text = "\U2022 response()\n\U2022 responseString(encoding: NSStringEncoding)\n\U2022 responseJSON(options: NSJS0NReading0ptions)\n\U2022 responsePropertyList(options: NSPropertyListRead0ptions)";
        top = 0;
        width = 487;
    }
)])

【问题讨论】:

    标签: json swift prefix swift2 alamofire


    【解决方案1】:

    在您调用 upload.responseJSON(_:completionHandler:) 的闭包参数中,您命名为 json 的参数将作为 Alamofire Result 枚举传递(请参阅 source)。

    您应该能够通过访问其value 属性来获取该枚举的关联数据,如下所示:

    upload.responseJSON  { _, _, json in
      print(json.value!)
    }
    

    此外,如果有机会,请查看SwiftyJSON(用于在 Swift 中处理 JSON 的流行库)。

    【讨论】:

    • 谢谢。但是现在,如果我这样做 case .Success(let upload, _, _): upload.responseJSON { _, _, _json in let json = JSON(_json.data!) if let ocr_results = json["text_block"][0]["text"].string { } } 我会在 let json = JSON(_json.data!) 得到一个错误,因为 _json.data 是 nil
    • @NMAC427 你想要_json.value!,如果你要从Result.Success 关联数据获取序列化响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 2016-06-02
    • 2016-02-23
    • 1970-01-01
    相关资源
    最近更新 更多