斯威夫特 - 可达性崩溃

时间:2016-04-21 21:18:00

标签: ios swift crash reachability reachability-swift

当按下UIButton以在完成操作之前检查互联网连接时,我调用方法testReachability()。这是使用Ashley Mill的可达性等级。

在第24行,我调用completed(),这样如果应用程序可以到达网络,那么它将完成关闭并继续执行其余操作。但是,应用程序变得很糟糕,并且在调试控制台中显示此错误:

“此应用程序正在从后台线程修改自动布局引擎,这可能导致引擎损坏和奇怪的崩溃。这将在将来的版本中导致异常。”

如果我在第26行调用completed(),那么应用程序运行完美,快速和平稳,直到我失去互联网连接/进入飞行模式。然后应用程序立即崩溃,xcode在按下按钮时失去与设备的连接。

我的问题是如何在检查可访问性时解决应用程序崩溃问题。

func testReachability(completed: DownloadComplete)
{
    let reachability: Reachability
    do {
        reachability = try Reachability.reachabilityForInternetConnection()
    } catch {
        return
    }

    reachability.whenReachable = { reachability in
        // this is called on a background thread, but UI updates must
        // be on the main thread, like this:
        dispatch_async(dispatch_get_main_queue())
        {
            if reachability.isReachableViaWiFi()
            {
                print("Reachable via WiFi")
            }
            else
            {
                print("Reachable via Cellular")
            }
        }
        completed()
    }

    reachability.whenUnreachable = { reachability in
        // this is called on a background thread, but UI updates must
        // be on the main thread, like this:
        dispatch_async(dispatch_get_main_queue())
        {
           self.presentReachabilityAlertController()
        }
    }

    do
    {
        try reachability.startNotifier()
    }
    catch
    {

    }
}

func presentReachabilityAlertController()
{
    let alert = UIAlertController( title: "Network Connection Lost", message:"Try Again", preferredStyle: .Alert)
    alert.addAction(UIAlertAction( title: "ok"  , style: .Default) { _ in } )
    presentViewController        ( alert, animated: true                   ) {      }
    connected = false
}

1 个答案:

答案 0 :(得分:0)

这听起来像完全需要在主线程上执行的调用。在sitecore_master_index内部时会这样做。尝试将调用完成内部dispatch_async,如下所示:

dispatch_async(dispatch_get_main_queue())

如果在飞行模式/离线状态下这不能解决问题,我认为我们需要更多代码来帮助您解决问题。如果您可以显示如何/何时调用此函数,则可以显示完整的回调,甚至是dispatch_async(dispatch_get_main_queue()) { if reachability.isReachableViaWiFi() { print("Reachable via WiFi") } else { print("Reachable via Cellular") } complete() } 函数,这将是有用的。