2017-06-20 39 views
1

进口基金会 进口SystemConfiguration如何检查3G,4G和SWIFT 2.2

公共类可达{

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(sizeofValue(zeroAddress)) 
    zeroAddress.sin_family = sa_family_t(AF_INET) 

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

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

    let isReachable = flags == .Reachable 
    let needsConnection = flags == .ConnectionRequired 

    return isReachable && !needsConnection 

} 

}

我现在用的是上面写的代码检查无线互联网连接互联网连接为我的应用程序,这只检查3G和W​​IFI连接。但我还需要检查4G连接。任何人都可以帮助我找到解决方案。

回答

3

这是来自Apple的Reachability,您需要下载并将Reachability.h/.m拖放到您的项目中。

然后import CoreTelephony并尝试在下面。

if let reachability = Reachability.forInternetConnection() { 
     reachability.startNotifier() 
     let status = reachability.currentReachabilityStatus() 
     if status == .init(0) { 
      // .NotReachable 
      print("Not Reachable") 
     } 
     else if status == .init(1) { 
      // .ReachableViaWiFi 
      print("Reachable Via WiFi") 

     } 
     else if status == .init(2) { 
      // .ReachableViaWWAN 
      let netInfo = CTTelephonyNetworkInfo() 
      if let cRAT = netInfo.currentRadioAccessTechnology { 
       switch cRAT { 
       case CTRadioAccessTechnologyGPRS, 
        CTRadioAccessTechnologyEdge, 
        CTRadioAccessTechnologyCDMA1x: 
        print("Reachable Via 2G") 
       case CTRadioAccessTechnologyWCDMA, 
        CTRadioAccessTechnologyHSDPA, 
        CTRadioAccessTechnologyHSUPA, 
        CTRadioAccessTechnologyCDMAEVDORev0, 
        CTRadioAccessTechnologyCDMAEVDORevA, 
        CTRadioAccessTechnologyCDMAEVDORevB, 
        CTRadioAccessTechnologyeHRPD: 
        print("Reachable Via 3G") 
       case CTRadioAccessTechnologyLTE: 
        print("Reachable Via 4G") 
       default: 
        fatalError("error") 
       } 
      } 
     } 
    } 
+0

如何使用这是视图控制器 – user3549189

+0

你是什么意思? – ovo

+0

使用您的代码我如何检查互联网连接...使用条件 – user3549189

相关问题