【发布时间】:2016-07-30 15:42:43
【问题描述】:
下面是我的代码
func contactForUpdates() -> Int {
//contact server for most recent version
let versionURL = settings.versionURL
if let url = URL(string: versionURL) {
do {
let contents = try NSString(contentsOf: url, usedEncoding: nil)
//NEXT LINE IS WHERE THE QUESTIONS LIES
return Int(contents as String)!
} catch {
// contents could not be loaded
processError("Current version could not be loaded.")
return Int(0)
}
} else {
// the URL was bad!
processError("Current version could not be loaded--URL was bad.")
return Int(0)
}
}
如果 URL 加载,它将返回一个整数。糟糕的 Internet 连接,例如需要在访问 Internet 之前登录的机场,不会返回整数,而是返回请求登录的完整 HTML 页面。使用return Int(contents as String)! 强制向下转换将产生错误fatal error: unexpectedly found nil while unwrapping an Optional value。
当我写这篇文章时,我假设这会运行 catch 语句,但它却返回了一个致命错误。我怎么能抓住这个?
【问题讨论】:
-
这不是直接回答问题,但我建议您考虑使用网络可达性库。它将捕获您可能没有想到的其他网络可访问性问题,并且可以执行诸如在网络确实变得可访问时异步触发您的版本检查之类的事情。 Cocoapods 上有很多。许多都是基于块的,因此您无需使用您编写的方法,而是将代码从成功案例移到您传递可达性库的块内。