我的代码如下:
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
。此代码与我在网络上看到的示例非常相似。
如果请求在该时间内完成,则不会发生致命错误。
我希望能够捕获超时错误。任何人都知道代码有什么问题吗?
答案 0 :(得分:2)
此行中的感叹号位于错误的位置
var data:NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)!
应该是,
var data:NSData! = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)