【问题标题】:unable to print json value with alamofire无法使用 alamofire 打印 json 值
【发布时间】:2018-11-17 17:28:14
【问题描述】:

我正在尝试使用 flickr API 获取数据,我使用 Alamofire 和 swiftyJSON 编写了一个简单的代码来从 flickr 获取这些数据,但是我能够打印数据大小但是当我尝试打印 json 时,我的 catch块运行。我的代码如下所示

func getPhotos(completion: @escaping CompletionHandler) -> Void {

        let parameter: [String: Any] = [
            "method": PHOTOS_METHOD,
            "api_key": FLICKR_API_KEY,
            "per_page": PER_PAGE,
            "page": PAGE,
            "format": FORMAT_TYPE,
            "nojsoncallback": JSON_CALLBACK]

        Alamofire.request(FLICKR_URL, method: .get, parameters: parameter, encoding: JSONEncoding.default, headers: HEADER).responseString { (response) in

            if response.result.error == nil {

                guard let data = response.data else {return}

                do {
                    if let json = try JSON(data: data).array {
                        print(json)
                    }
                    completion(true)
                } catch {
                    print("eroorrrre")
                    completion(false)
                }

                print("CALL CORRECT")
                print(data)

                completion(true)
            }
            else {
                completion(false)
                debugPrint(response.result.error as Any)
            }
        }
    }

我的控制台日志

eroorrrre
CALL CORRECT
128 bytes

我不确定我在这里做错了什么,任何帮助都会得到帮助

【问题讨论】:

  • 永远不会在 catch 子句中打印像 eroorrrre 这样的无意义文字字符串,打印 error 实例。它很可能向您显示什么您在这里做错了。如果出现错误,您将调用completion 两次。不要那样做。
  • 感谢我会更正

标签: swift alamofire flickr swifty-json


【解决方案1】:

试试这个

Alamofire.request(FLICKR_URL, method: .get, parameters: parameter, headers: HEADER).responseJSON { response in // call responseJSON instead of responseString

    if response.result.isSuccess { // If http request is success

        let json: JSON = JSON(response.result.value!) // JSON format from SwiftyJSON (I suppose you are using it)

        guard let data = json.array else { // You suppose that json is array of objects
            print("Unexpected JSON format")
            completion(false)
        }

        print(data) 
        completion(true)

    } else {
        print(response.error)
        completion(false)
    }
}

【讨论】:

  • 谢谢,这工作正常,但我的代码为什么不能工作?我一直使用它,它总是有效的
  • @King 在你的情况下 response.data 的 JSON 格式不正确
  • 嗨,请帮助检查这个问题stackoverflow.com/questions/53360597/…
猜你喜欢
  • 1970-01-01
  • 2018-05-15
  • 2020-12-02
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
  • 2019-09-19
相关资源
最近更新 更多