【问题标题】:checking internet connectivity for cellular networks in ios using Swift使用 Swift 检查 ios 中蜂窝网络的互联网连接
【发布时间】:2016-12-21 08:59:30
【问题描述】:

我使用 stack Overflow 的解决方案来检查互联网连接它适用于 wifi 网络,但不适用于蜂窝网络

public class YASConnectivity {
class func isConnectedToNetwork() -> 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)
    return (isReachable && !needsConnection)
}

}

如何检查蜂窝网络的 Internet 连接?

我在尝试 Rock 的解决方案时遇到此错误

【问题讨论】:

    标签: ios swift reachability connectivity cellular-network


    【解决方案1】:

    尝试使用这个第三方库: Reachability

    并编写以下代码:

    let reachability = Reachability.reachabilityForInternetConnection()
    
    reachability?.whenReachable = { reachability in
        // keep in mind this is called on a background thread
        // and if you are updating the UI it needs to happen
        // on the main thread, like this:
        dispatch_async(dispatch_get_main_queue()) {
            if reachability.isReachableViaWiFi() {
                print("Reachable via WiFi")
            } else {
                print("Reachable via Cellular")
            }
        }
    }
    reachability?.whenUnreachable = { reachability in
        // keep in mind this is called on a background thread
        // and if you are updating the UI it needs to happen
        // on the main thread, like this:
        dispatch_async(dispatch_get_main_queue()) {
            print("Not reachable")
        }
    }
    
    reachability?.startNotifier()
    

    【讨论】:

    • 我究竟需要在哪里执行此操作?
    • @Byte 你可以在你的主视图控制器或应用程序委托中执行它,我建议使用一个包装它的对象,这样你就可以拥有一个干净的代码。无论如何,第一步可以在应用程序委托中调用它,并使用选项委托启动
    • 您能否以返回 bool 连接的函数形式更新您的答案?谢谢
    【解决方案2】:

    首先将 Reachability.swift 文件添加到您的项目中并使用此代码。

    class func checkNetworkConnection() -> Bool 
    {
        let reachable = Reachability.reachabilityForInternetConnection()
    
        if reachable.isReachable() || reachable.isReachableViaWiFi()
        {
            return true
        }
        else
        {
            print("Mobile Data")
           return false
    
        }
    }
    

    希望对你有帮助……

    【讨论】:

    • 可以说我的移动数据已开启。但我没有互联网连接。这行得通吗?
    • 它只会打印移动数据。
    • 对不起,它不适用于蜂窝网络。如果我的移动数据已开启且我没有任何互联网套餐,则返回 true。
    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2015-08-20
    • 1970-01-01
    相关资源
    最近更新 更多