Connection is always giving me false?

69 Views Asked by At

I am using Reachability.swift to test the internet connection is (off/On) and the server is (live/dead) the server check work fine but internet Connection is always giving me false?

   @IBAction func TestNetwork(_ sender: Any) {
        var internetConnection = "❌"
        var serverStatus  = "❌"
        var message = " \(internetConnection) internet connection \n   \(serverStatus) MHS server\n  "            
        let reachability = Reachability(hostname:"google.com")
        if (reachability?.connection !=  .none ) {
              serverStatus = "✅"
             message = " \(internetConnection) internet connection \n   \(serverStatus) goole server\n  "

        } else {
           serverStatus =  "❌"
            message = " \(internetConnection) internet connection \n   \(serverStatus) google server\n  "
        }
        if (reachability?.connection == .wifi && reachability?.connection == .cellular) {
            internetConnection = "✅"
            message = " \(internetConnection) internet connection \n   \(serverStatus) google server\n  "            
        } else {
            internetConnection = "❌"
            message = " \(internetConnection) internet connection \n   \(serverStatus) google  server\n  "
        }

        let alertController = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(
            title: "OK", style: .default, handler: nil)
        alertController.addAction(defaultAction)
        self.present(alertController, animated: true, completion: nil)
    }
1

There are 1 best solutions below

0
On BEST ANSWER

Connection is an enum with 3 cases:

enum Connection {
    case none, wifi, cellular
}

Since your reachability?.connection can only be one of these, you need to change your check from && to ||.

Change:

if (reachability?.connection == .wifi && reachability?.connection == .cellular) {
        internetConnection = "✅"
        message = " \(internetConnection) internet connection \n   \(serverStatus) google server\n  "            
    }

To:

if (reachability?.connection == .wifi || reachability?.connection == .cellular) {
        internetConnection = "✅"
        message = " \(internetConnection) internet connection \n   \(serverStatus) google server\n  "            
    }