NetworkReachabilityManager 或 Reachability 无法识别在没有互联网的情况下连接 wifi

Connecting wifi without internet not recognised with NetworkReachabilityManager or Reachability

尝试检查互联网连接时遇到问题。 在没有互联网的 wifi 上使用 alamofire NetworkReachabilityManager 时,如下所示:

import Alamofire

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

这是实现:

    if Connectivity.isConnectedToInternet() {
        print("Yes! internet is available.")
    } else {
        print("No! internet is not available.")
    }

我得到:“是的!互联网可用。”当没有活动的互联网连接时(使用 Safari 检查)。

也尝试了这个具有可达性的:

import Reachability

 class ReachabilityManager: NSObject {

var reachability: Reachability!

static let sharedInstance: NetworkManager = { return NetworkManager() }()


override init() {
    super.init()
    
    reachability = Reachability()!
    
    NotificationCenter.default.addObserver(
        self,
        selector: #selector(networkStatusChanged(_:)),
        name: .reachabilityChanged,
        object: reachability
    )
    
    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
}

@objc func networkStatusChanged(_ notification: Notification) {
    // Do something globally here!
}

static func stopNotifier() -> Void {
    do {
        try (NetworkManager.sharedInstance.reachability).startNotifier()
    } catch {
        print("Error stopping notifier")
    }
}

static func isReachable(completed: @escaping (NetworkManager) -> Void) {
    if (NetworkManager.sharedInstance.reachability).connection != .none {
        completed(NetworkManager.sharedInstance)
    }
}

static func isUnreachable(completed: @escaping (NetworkManager) -> Void) {
    if (NetworkManager.sharedInstance.reachability).connection == .none {
        completed(NetworkManager.sharedInstance)
    }
}

static func isReachableViaWWAN(completed: @escaping (NetworkManager) -> Void) {
    if (NetworkManager.sharedInstance.reachability).connection == .cellular {
        completed(NetworkManager.sharedInstance)
    }
}

static func isReachableViaWiFi(completed: @escaping (NetworkManager) -> Void) {
    if (NetworkManager.sharedInstance.reachability).connection == .wifi {
        completed(NetworkManager.sharedInstance)
    }
}
}

实现是:

NetworkManager.isReachable { networkManagerInstance in
    print("Network is available")
}

NetworkManager.isUnreachable { networkManagerInstance in
    print("Network is Unavailable")
}

我做错了什么?

您是如何检查连接的?你有没有试过像下面这样联系任何主机。

do {
        Network.reachability = try Reachability(hostname: "www.google.com")
        do {
            try Network.reachability?.start()
        } catch let error as Network.Error {
            print(error)
        } catch {
            print(error)
        }
    } catch {
        print(error)
    }