How to check internet connection in Swift 3 or Swift 4?

12,865

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


}
Share:
12,865
TechChain
Author by

TechChain

I have 4+ of experience of overall experience.Currently working on Hyperledger Fabric blockchain framework. I have strong knowledge of Objective c, Swift.I have developed lot of apps from chat app, finance apps,location & map based apps.

Updated on June 28, 2022

Comments

  • TechChain
    TechChain almost 2 years

    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.

  • Arildo Junior
    Arildo Junior over 7 years
    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.
  • mxlhz
    mxlhz over 3 years
    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: github.com/Alamofire/Alamofire/issues/2275