连接总是给我假的?

时间:2019-04-03 15:10:50

标签: ios swift reachability reachability-swift

我正在使用Reachability.swift来测试Internet连接(关闭/打开)并且服务器处于(活动/死机)服务器检查正常,但是Internet Connection总是错误?

   @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 个答案:

答案 0 :(得分: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  "            
    }