如何从swift2.0,xcode7.3中的http请求中获取JSON数据

时间:2016-04-06 23:34:02

标签: json swift http get

我正在尝试编写一种方法来扫描条形码,然后使用http rest调用从服务器获取一些JSON数据。 Alamofire现在不工作,我尝试了很多不同的方式。

这是我现在所拥有的:

let getEndpoint: String = "45.55.63.218:8080/food?foodidentifier=\(code)"
    let requestURL: NSURL = NSURL(string: getEndpoint)!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {
            print("Everyone is fine, file downloaded successfully.")
            do{
                //let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

            }catch {
                print("Error with Json: \(error)")
            }

        }
    }
task.resume()

我收到一条错误消息: 致命错误:在展开Optional值时意外发现nil (lldb)在线:let httpResponse = response as! NSHTTPURLResponse

1 个答案:

答案 0 :(得分:0)

问题是如果NSHTTPURLResponseresponse,强制转换为nil将会失败(例如,如果出现某些错误导致请求无法成功发出,例如在这种情况下,URL字符串缺少http://方案前缀;但是这可能发生在任何各种问题上,因此必须优雅地预测和处理网络错误)。当处理来自网络请求的响应时,除非您首先确认该值是有效且非nil,否则应该刻意避免强制解包/转换。

我建议:

  • 使用guard语句安全地检查nil值;
  • 在检查状态代码之前,检查data不是nilerrornil;

所以,这可能会产生:

let task = session.dataTaskWithRequest(urlRequest) { data, response, error in
    guard data != nil && error == nil else {
        print(error)
        return
    }

    guard let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200 else {
        print("status code not 200; \(response)")
        return
    }

    print("Everyone is fine, file downloaded successfully.")
    do {
        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
        print(json)
    } catch let parseError {
        print("Error with Json: \(parseError)")
    }
}
task.resume()
相关问题