使用SWIFT检查互联网连接

使用SWIFT检查互联网连接

当我试图在我的iPhone上检查互联网连接时,我会发现很多错误。有人能帮我解决这个问题吗?

守则:

import Foundationimport SystemConfigurationpublic class Reachability {class func isConnectedToNetwork() -> Bool {

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

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

    var flags: SCNetworkReachabilityFlags = 0

    if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
        return false
    }

    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection) ? true : false}}

如果它不可读,错误1说:

“int”不可转换为“SCNetworkReacabilityFlags”

错误2和3:

无法找到接受所提供的参数的“init”重载


青春有我
浏览 722回答 3
3回答

一只名叫tom的猫

对于SWIFT 3,SWIFT 4(与蜂窝和Wi-Fi一起工作):import SystemConfigurationpublic class Reachability {     class func isConnectedToNetwork() -> Bool {         var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0),          sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))         zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))         zeroAddress.sin_family = sa_family_t(AF_INET)         let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {             $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in                 SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)             }         }         var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)         if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {             return false         }         /* Only Working for WIFI         let isReachable = flags == .reachable         let needsConnection = flags == .connectionRequired         return isReachable && !needsConnection         */         // Working for Cellular and WIFI        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0         let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0         let ret = (isReachable && !needsConnection)         return ret    }}用法:if Reachability.isConnectedToNetwork(){     print("Internet Connection Available!")}else{     print("Internet Connection not Available!")}
打开App,查看更多内容
随时随地看视频慕课网APP