iOS - 超时失败的同步请求
iOS - Synchronous Request with Timeout failing
我有这样的代码:
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")
如果请求花费的时间太长,NSURLConnection.sendSynchronousRequest(...)
调用有一个 fatal error: unexpectedly found nil while unwrapping an Optional value
。我不确定发生了什么。当我查看调试 window 时,唯一的 nil
变量是 response
。此代码看起来与我在网上看到的示例非常相似。
如果请求在规定时间内完成,则不会发生致命错误。
我希望能够捕获超时错误。有人知道代码有什么问题吗?
你在这一行的错误位置有感叹号,
var data:NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)!
应该是,
var data:NSData! = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)
我有这样的代码:
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")
如果请求花费的时间太长,NSURLConnection.sendSynchronousRequest(...)
调用有一个 fatal error: unexpectedly found nil while unwrapping an Optional value
。我不确定发生了什么。当我查看调试 window 时,唯一的 nil
变量是 response
。此代码看起来与我在网上看到的示例非常相似。
如果请求在规定时间内完成,则不会发生致命错误。
我希望能够捕获超时错误。有人知道代码有什么问题吗?
你在这一行的错误位置有感叹号,
var data:NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)!
应该是,
var data:NSData! = NSURLConnection.sendSynchronousRequest(request1, returningResponse: &response, error: &error)