0

我正在使用 Reachability.swift 来测试互联网连接是(关闭/打开)并且服务器是(活/死)服务器检查工作正常但互联网连接总是给我错误?

   @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)
    }
4

1 回答 1

1

Connection 是一个包含 3 种情况的枚举:

enum Connection {
    case none, wifi, cellular
}

由于您reachability?.connection只能是其中之一,因此您需要将支票从 更改&&||

改变:

if (reachability?.connection == .wifi && reachability?.connection == .cellular) {
        internetConnection = "✅"
        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  "            
    }
于 2019-04-03T20:00:05.567 回答