检查是否有可用的互联网,包括4G

时间:2016-06-21 01:40:14

标签: ios swift

我试图检查我的用户是否有可用于执行某些任务的互联网,例如登录其用户帐户。我目前正在使用使用的可访问性类来工作,但现在它只能检查是否有wifi连接。如果我的手机连接到4G或移动数据,它会说没有互联网连接。还有其他方法可以检查互联网连接吗?

提前感谢您的帮助! : - )

import Foundation
import SystemConfiguration

public 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(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
}

}

2 个答案:

答案 0 :(得分:1)

打开一个新的Swift文件并包括这个类: -

import Foundation
import SystemConfiguration

public class Reachability {

    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)
   }
 }

然后你可以检查另一个类的连接,比如

if Reachability.isConnectedToNetwork() { 
  //Has Connectivity
} else {
  //No connection
}

答案 1 :(得分:0)

Swift 3版

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 = []
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)
    return (isReachable && !needsConnection)
}