Search code examples
swiftreachability

Swift 3 Reachability From Button


I am using the Reachability library on github found here. I want to check whether device is online by clicking on a button. I am new to Reachability so from what I have seen, you have to start listening for the change and then test the connection and then stop listening. So far I have this in my button action but when I click the button, nothing gets printed to console.

var reachability: Reachability!
do {
    try reachability?.startNotifier()
} catch {
    print("Unable to start notifier")
}


reachability?.whenReachable = { reachability in

    DispatchQueue.main.async {
        if reachability.isReachableViaWiFi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
}


reachability?.whenUnreachable = { reachability in

    DispatchQueue.main.async {
        print("Not reachable")
    }
}


reachability?.stopNotifier()

Solution

  • You got nil because of using implicitly unwrapped optional.

    Replace,

    var reachability: Reachability!
    

    to

    let reachability = Reachability()
    

    Try below,

    let reachability = Reachability()
    
    do {
        try reachability?.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
    
    
    if reachability?.isReachable == true{
    
        if reachability?.isReachableViaWiFi == true{
            print("Reachable via WiFi")
        } else if reachability?.isReachableViaWWAN == true{
            print("Reachable via WWAN simulator")
        }else{
            print("Reachable via Cellular")
        }
    
    }else{
        print("Not reachable")
    }
    
    
    reachability?.stopNotifier()