2

I have tried checking internet connection in Swift 3 but the code is not working for me.

 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(&zeroAddress) {
      SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: UInt32(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
  }

I have also imported the SystemConfiguration framework. Please suggest how to check.

clemens
  • 14,173
  • 11
  • 38
  • 52
TechChain
  • 7,104
  • 20
  • 81
  • 193
  • 1
    Define "not working". – rmaddy Nov 11 '16 at 04:44
  • You can check this link for reference. It contains the network check when connected or when it gets disconnected. http://stackoverflow.com/questions/40066530/my-reachability-notifier-is-only-able-to-be-called-once/40068225#40068225 – Rajan Maheshwari Nov 11 '16 at 05:12

3 Answers3

0
   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()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}

problemstucks.com

Parth
  • 528
  • 5
  • 14
  • 2
    If you are connected to a wi-fi but not able to connect to the internet (open a google page) still it returns true for reachable. It's wrong. – Arildo Junior Feb 02 '17 at 18:59
0

Latest swift3 code

Here The easiest way to check for internet connectivity is to use the iOS reachability api. check this bellow link and download add reachability file to your projects .you must and should be added systemconfiguration framework is added to the project

 [1]: https://github.com/ashleymills/Reachability.swift/tree/feature/ios10

After finishing above work just write this code for checking networking connection.here i am writing some alert message also.

    func networkStatusChanged(_ notification: Notification) {
    let userInfo = (notification as NSNotification).userInfo
    print(userInfo!)
}
func interNetChecking( )   {
    let status = Reach().connectionStatus()


    switch status {
    case .unknown, .offline:

        let alert = UIAlertController(title: "Check", message: "Internet Connection is Required at first time running the app to load images and videos ", preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))

        DispatchQueue.main.async(execute: {
            self.present(alert, animated: true, completion: nil)
        })


        print("Not connected")
    case .online(.wwan):
        print("Connected via WWAN")
    case .online(.wiFi):
        print("Connected via WiFi")
    }


}
0

In case of Alamofire

import Alamofire

// Add in your viewDidLoad() or in AppDelegate like this

let reachabilityManager = NetworkReachabilityManager()
    reachabilityManager.listener = { status in

        switch status {

        case .notReachable:
            print("The network is not reachable")
            self.onInternetDisconnection()

        case .unknown :
            print("It is unknown whether the network is reachable")
            self.onInternetDisconnection() // not sure what to do for this case

        case .reachable(.ethernetOrWiFi):
            print("The network is reachable over the WiFi connection")
            self.onInternetConnection()

        case .reachable(.wwan):
            print("The network is reachable over the WWAN connection")
            self.onInternetConnection()

        }
    }
Rohan Dave
  • 253
  • 1
  • 7
  • Don't forget to call `reachabilityManager.startListening() ` or the listener won't be called at all. Here is an interesting link as there are things to consider on a simulator with this code: https://github.com/Alamofire/Alamofire/issues/2275 – mxlhz Nov 14 '20 at 18:27