Tim Tim - 5 months ago 77
Swift Question

Check if Internet is available including 4G

I'm trying to check if my user has internet available to perform certain tasks such as log in to their user account. I'm currently using the reachability class that used to work but now it only works to check if there's a wifi connection. If my phone is connected to 4G or mobile data, it'll say that there is no internet connection. Is there another way I can check for internet connection?

Thanks for your help in advance! :-)

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
}


}

Answer

Open a new Swift File and Include this class :-

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

Then you can check connectivity in another class like

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