Search code examples
iosswiftalamofirereachability

Attempt to check internet connection on iOS device with Alamofire


I use following code to check internet connection:

class Reachability {

    let networkReachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")

    func checkForReachability() {
        self.networkReachabilityManager?.listener = { status in
            print("Network Status: \(status)")
            switch status {
            case .notReachable:
                print("no internet connection detected")
            //Show error here (no internet connection)
            case .reachable(_), .unknown:
                print("internet connection availible")
            }
        }
        self.networkReachabilityManager?.startListening()
    }
}

When connection is exist, it successfully call block in .reachable. But in case of connection absence nothing called, why?

I call it like that (keeping reference to class, so it's not released)

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    let reachabilityManager = Reachability()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        reachabilityManager.checkForReachability()
        return true
    }

Solution

  • create the common class for check the connectivity

    import Foundation
    import Alamofire
    
    class Connectivity {
        class func isConnectedToInternet() -> Bool {
            return NetworkReachabilityManager()!.isReachable
        }
    }
    

    and call the function where you need

    if !Connectivity.isConnectedToInternet() {
        // show Alert
        return
    }