一尘不染

如何在Alamofire中使用NetworkReachabilityManager

swift

我想要类似于AFNetworkingSwift中带有Alamofire NetworkReachabilityManager的Objective-
C的功能:

//Reachability detection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN: {
            [self LoadNoInternetView:NO];
            break;
        }
        case AFNetworkReachabilityStatusReachableViaWiFi: {
            [self LoadNoInternetView:NO];
            break;
        }
        case AFNetworkReachabilityStatusNotReachable: {
            break;
        }
        default: {
            break;
        }
    }
}];

我目前正在使用侦听器来了解网络状态的变化

let net = NetworkReachabilityManager()
net?.startListening()

有人可以描述如何支持这些用例吗?


阅读 849

收藏
2020-07-07

共1个答案

一尘不染

我自己找到了答案,即通过如下所述只写一个带有闭包的侦听器:

let net = NetworkReachabilityManager()

net?.listener = { status in
    if net?.isReachable ?? false {

    switch status {

    case .reachable(.ethernetOrWiFi):
        print("The network is reachable over the WiFi connection")

    case .reachable(.wwan):
        print("The network is reachable over the WWAN connection")

    case .notReachable:
        print("The network is not reachable")

    case .unknown :
        print("It is unknown whether the network is reachable")

    }
}

net?.startListening()
2020-07-07