加载选项卡后,请随时检查连接

时间:2016-08-18 03:20:28

标签: ios swift

在我的项目中,我有在本网站上找到的代码,用于检查用户是否没有任何互联网(没有wifi或手机)。当没有连接的人打开选项卡时,代码工作,但是当他们首先打开选项卡然后失去连接时,它无法检测到。如何在加载选项卡后触发该功能并且之后失去连接?以下是代码:

import SystemConfiguration

func connectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }) else {
        return false
    }

    var flags : SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.Reachable)
    let needsConnection = flags.contains(.ConnectionRequired)

    // For Swift 3, replace the last two lines by
    // let isReachable = flags.contains(.reachable)
    // let needsConnection = flags.contains(.connectionRequired)


    return (isReachable && !needsConnection)
}

0 个答案:

没有答案