【问题标题】:link gives back nil and crashes my app when using Alamofire and SwiftyJSON to get JSON from URL当使用 Alamofire 和 SwiftyJSON 从 URL 获取 JSON 时,链接返回 nil 并使我的应用程序崩溃
【发布时间】:2016-04-17 11:39:56
【问题描述】:

我不熟悉在线提出请求。我正在使用 Alamofire 和 swiftyJSON 从 URL 取回数据,但它一直在崩溃,说链接返回 nil。是因为提供的链接最后不是 .json 吗? (顺便说一下,我添加的链接是假的,不能添加真正的,但结构是一样的)。

let URL = "https://www.thisurlisntreal.com/api/folder?key="12345FGhbfdgn3456fgdnf2345redfs?56"
        Alamofire.request(.GET, URL).validate().responseJSON { response in
            switch response.result {
            case .Success:
                if let value = response.result.value {
                    let json = JSON(value)
                    print("JSON: \(json)")
                }
            case .Failure(let error):
                print(error)
            }
        }

链接只有这个数据:

{"results":[{"id":1,"fromDate":"2015-03-18","toDate":"2016-04-23","url":"blabliebloe","producer":{"id":1,"name":"theproducer"}}]}

我在Alamofire.request(.GET, URL).validate().responseJSON { response in 遇到崩溃,告诉我unexpectedly found nil while unwrapping an Optional value。我用多个格式化程序和验证器检查了 JSON,一切都成功了,所以这不是问题。

更新: 我只是使用了一个不同的链接 (http://refine.taxonomics.org/gbifchecklists/reconcile?query=Crepidomanes%20minutum),这确实有效...我不知道这怎么可能,但它可能与服务器端相关吗?

【问题讨论】:

    标签: json swift url alamofire swifty-json


    【解决方案1】:

    尝试像这样替换开关语句:

    switch response.result {
                    case .Success(let data):
                        let json = JSON(data)
                    case .Failure(let error):
                        print(error.localizedDescription())
                    }
    

    【讨论】:

    • 试过了,但是应用已经在Alamofire.request(.GET, URL).validate().responseJSON崩溃了,说fatal error: unexpectedly found nil while unwrapping an Optional value
    【解决方案2】:

    也许您应该检查您的 URLRequest 是否设置正确,以期望使用以下几行之一得到 json 答案:

    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-03
      相关资源
      最近更新 更多