ios - 应用程序在飞行模式下启动时崩溃

标签 ios swift reachability reachability-swift

我目前正在使用 Ashley Mill 的 Reachability Class。如果应用程序通过网络连接启动,那么我可以在连接可用性之间切换而不会出现任何问题,并且能够正确显示网络连接警报 Controller 。但是,如果应用程序在没有互联网连接/飞行模式下启动时启动,它会突然崩溃。

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 应用程序启动并显示没有网络连接的警报而不是突然崩溃?

错误消息:

fatal error: unexpectedly found nil while unwrapping an Optional value

但我认为更改可达性会在 else 语句中捕获此内容并弹出错误消息?

enter image description here

最佳答案

reachability.isReachableViaWiFi() if 语句中的 else 不应该是:connected = false 吗?

关于ios - 应用程序在飞行模式下启动时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36510185/

相关文章:

ios - 为什么 Swift Firebase auth() 响应晚?

ios - 5星级评级系统数据库设计

objective-c - 如何使用Reachability类来检测网络状态?

ios - 在运行 iOS 6 的 iPhone 上删除 UIStatusBarStyle Black Opaque 下面的圆角

swift - UIImagePickerController Gallery 委托(delegate)未调用

iphone - 可达性中的 UIAlertView 异常

iphone - 在后台获取可达性更改通知

ios - RESideMenu : Side menu for iOS 7 to support both left and right menu

ios - 具有巨大 Canvas 的绘画应用程序

iphone - 应用商店反馈问题