我目前正在使用 Ashley Mill 的可达性类。如果应用程序通过网络连接启动,那么我可以在连接可用性之间切换而不会出现任何问题,并且能够正确显示网络连接警报控制器。但是,如果应用程序在没有互联网连接/飞行模式下启动时启动应用程序,它会突然崩溃。
override func viewDidLoad()
{
super.viewDidLoad()
setUpReachability (nil)
}
func setUpReachability(hostName: String?)
{
do
{
let reachability = try hostName == nil ? Reachability.reachabilityForInternetConnection() : Reachability(hostname: hostName!)
self.reachability = reachability
try! self.reachability?.startNotifier()
}
catch ReachabilityError.FailedToCreateWithAddress(let address)
{
print("\(address)")
return
} catch {}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.reachabilityChanged(_:)), name: ReachabilityChangedNotification, object: reachability)
}
func reachabilityChanged(notification: NSNotification)
{
let reachability = notification.object as! Reachability
if reachability.isReachable()
{
if reachability.isReachableViaWiFi()
{
connected = true
}
else
{
connected = true
}
}
else
{
let alert = UIAlertController( title: "No Network Connection Available", message:"Try Again", preferredStyle: .Alert)
alert.addAction(UIAlertAction( title: "Will Do!" , style: .Default) { _ in } )
presentViewController ( alert, animated: true ) {}
connected = false
}
}
可以做些什么来让 iPhone 应用程序启动并显示没有网络连接的警报而不是突然崩溃?
错误信息:
致命错误:在展开可选值时意外发现 nil
但我认为可达性改变会在 else 语句中捕捉到这一点并弹出错误消息?