iOS - 超时失败的同步请求

时间:2015-01-30 01:51:55

标签: 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: unexpectedly found nil while unwrapping an Optional value电话就会NSURLConnection.sendSynchronousRequest(...)。我不知道发生了什么事。当我查看调试窗口时,唯一的nil变量是response。此代码与我在网络上看到的示例非常相似。

如果请求在该时间内完成,则不会发生致命错误。

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

1 个答案:

答案 0 :(得分:2)

此行中的感叹号位于错误的位置

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

应该是,

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