我使用继承 BaseViewController 的 viewController。在 BaseViewController 的方法“viewDidLoad”中调用函数“monitorNetworkStatus()”。
private func monitorNetworkStatus() {
ReachabilityManager.shared.startMonitoring { [weak self] (status, presentingVC) in
print(self?.description)
}
}
ReachabilityManager 是一个单例。startMonitoring 函数是这样的
func startMonitoring(reachabilityStatus: @escaping (_ status: AFNetworkReachabilityStatus, _ presentingVC: UIViewController?) -> Void) {
AFNetworkReachabilityManager.shared().setReachabilityStatusChange { [weak self] (status) in
if status != self?.networkStatus {
// Only notify when status toggling between reachable and not reachable
if (self?.networkStatus == .notReachable &&
(status == .reachableViaWiFi || status == .reachableViaWWAN)) ||
status == .notReachable {
reachabilityStatus(status, self?.getPresentingViewController())
}
self?.networkStatus = status
}
}
AFNetworkReachabilityManager.shared().startMonitoring()
当网络状态发生变化时,它偶尔会打印 nil。