ios - 使用 Swift 检查 ios 中蜂窝网络的互联网连接

标签 ios swift reachability connectivity cellular-network

我使用了堆栈溢出的解决方案来检查互联网连接它适用于 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 的解决方案时遇到此错误

enter image description here

最佳答案

尝试使用这个第三方库: 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()

关于ios - 使用 Swift 检查 ios 中蜂窝网络的互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38950267/

相关文章:

ios - AVCAPTURE 图像方向

ios - 可达性返回错误状态

ios - 当可达性连接丢失时显示警报 View

ios - 被宠坏的模拟器 xcode 9. 作为一个破电视

ios - 对象从字典数组到数组

ios - 需要从 NSArray 或 NSMutableArray 存储/检索对象

swift - 使用 Firebase (iOS-Swift) 进行用户读/写数据存储

swift - 使用 Parse 和 Swift 返回具有指针 ID 的所有对象

ios - 如何在 tableview swift 中显示复选标记?

iphone - 可达性图形叠加