iOS - 超时失败的同步请求

标签 ios http swift request synchronous

我有这样的代码:

let urlPath: String = "https://github.com/zemirco/sf-city-lots-json/raw/master/citylots.json"
var url: NSURL = NSURL(string: urlPath)!
var request1: NSURLRequest = NSURLRequest(URL: url, 
                                  cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, 
                              timeoutInterval: 1)

var response:NSURLResponse?;
var error:NSError?;

/*** the follow line is giving the error ***/
var data:NSData =  NSURLConnection.sendSynchronousRequest(
                                                  request1, 
                               returningResponse: &response, 
                                           error: &error)!

if( error != nil) {
    println ("ERROR")
} else {
    println(response)
    self.config = (NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary)

}
println("Done with Synchronous Request")

如果请求花费的时间太长,则会出现 fatal error: expectedly found nil while unwrapping an Optional value for the NSURLConnection.sendSynchronousRequest(...) 调用。我不确定发生了什么。当我查看调试窗口时,nil 的唯一变量是 response。此代码看起来与我在网络上看到的示例非常相似。

如果请求在时间内完成,则不会发生 fatal error 。

我希望能够捕获超时错误。有人知道代码有什么问题吗?

最佳答案

你在这一行的错误位置有感叹号,

var data:NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)!

应该是,

var data:NSData! =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)

关于iOS - 超时失败的同步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28228011/

相关文章:

ios - UIImageView 上的 UIGestureRecognizer

ios - UIButton 添加目标选择器不起作用

language-agnostic - 是否有普遍可用的 HTTPS POST 冒烟测试?

ios - Nib IBOutlet 导致应用程序崩溃

ios - 在 iOS 应用程序中使用 JSON 的最佳方式是什么?

scala - 如何从 Scala Play 中以 # 分隔的 url 中提取参数

javascript - JQuery 创建元素并在单击它时执行函数

ios - UIBarButtonItem Frame 在旋转动画后变化

ios - Swift getter 覆盖非计算变量

ios - 计算 iPhone 移动的短垂直距离