【问题标题】:Swift AsynchronousRequest response cannot be readSwift AsynchronousRequest 响应无法读取
【发布时间】:2016-01-22 12:53:52
【问题描述】:

我正在尝试从用 Swift 编写的 iOS 应用程序连接到数据库。我找不到替代所有其他功能的功能,这些功能在最新的 iOS 更新(9.2?)中被标记为已弃用。其中一些函数是 sendSynchronousRequest 和 sendAsynchronousRequest。

我想从数据库中读取数据和响应。我正在使用以下代码:

 NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
        let res = response as! NSHTTPURLResponse
        if(res.statusCode >= 200 && res.statusCode < 300) {
            let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        }
    })

我在第一行遇到错误:

从“(NSURLResponse?, NSData?, NSError?) throws -> Void' 类型的抛出函数到非抛出函数类型“(NSURLResponse?, NSData?, NSError?) -> Void”的无效转换

但是,当我注释掉 if 语句中的行(让 jsonData:NSDictionary = try ...)时,错误消失了。

我知道这个功能已被弃用;我找不到其他任何东西。

如何才能正确读取 AsynchronousRequest 的响应?

【问题讨论】:

    标签: ios database swift


    【解决方案1】:

    您缺少 do/catch

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
        let res = response as! NSHTTPURLResponse
        do {
        if(res.statusCode >= 200 && res.statusCode < 300) {
            let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
        }
        } catch {
    
        }
    }
    

    但是在 swift 中更简单更好的方法是这个网络库:Alamofire

    例子:

    Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
             .responseJSON { response in
                 print(response.request)  // original URL request
                 print(response.response) // URL response
                 print(response.data)     // server data
                 print(response.result)   // result of response serialization
    
                 if let JSON = response.result.value {
                     print("JSON: \(JSON)")
                 }
             }
    

    【讨论】:

      猜你喜欢
      • 2021-05-26
      • 2014-06-13
      • 1970-01-01
      • 2020-03-23
      • 2019-10-27
      • 1970-01-01
      • 2012-03-30
      • 2016-05-31
      相关资源
      最近更新 更多