0

我试图使用 Apple 为我们提供处理网络问题的网络框架来实现网络连接。

我所做的是: 1.每当应用程序处于活动状态时 - 我开始监控网络 2.每当应用程序进入后台时 - 我取消监控以降低电池电量的影响

每当我进入后台并再次返回应用程序时,我都会遇到这个问题,它不会再次监视,因为我们无法再次分配监视器实例。我们需要创建新的监控实例来重新开始监控

我正在尝试尽可能地减少冗余代码

所以要实现所有的边缘情况

以下是我的方法:-

网络监视器文件

 import Foundation
 import Network

 final class NetworkMonitor {

private let monitor: NWPathMonitor =  NWPathMonitor()

public private(set) var isConnected:Bool = false

public private(set) var connectionType:ConnectionType = .unknown

 init() {
    print("init")
    let queue = DispatchQueue.global(qos: .background)
    monitor.start(queue: queue)
}

public enum ConnectionType {
    case cellular
    case wifi
    case ethernet
    case unknown
}


public func startMonitoring() {

    monitor.pathUpdateHandler = { [weak self] path in
        self?.isConnected = path.status == .satisfied
        self?.getConnectionType(path)
        NotificationCenter.default.post(name: NSNotification.Name("connectionType"),
                                        object: nil)
    }
   }

public func stopMonitoring() {
      monitor.cancel()
}

private func getConnectionType(_ path:NWPath) {
   
    if path.usesInterfaceType(.wifi) {
        connectionType = .wifi
    } else if path.usesInterfaceType(.cellular) {
        connectionType = .cellular
    } else if path.usesInterfaceType(.wiredEthernet) {
        connectionType = .ethernet
    } else {
        connectionType = .unknown
    }
    
}

}

这是我要监控的视图:

   class ViewController: UIViewController {

private var networkMonitor:NetworkMonitor?

private let notificationCenter = NotificationCenter.default
private let networkConnectivityView = NetworkConnectivityView()


override func viewDidLoad() {
    super.viewDidLoad()
    
    view.addSubview(networkConnectivityView)
    notificationCenter.addObserver(self,
                                   selector: #selector(listeningNetworkConnection),
                                   name: NSNotification.Name("connectionType"),
                                   object: nil)
    
    notificationCenter.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
    
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
    
}
  

@objc func appDidBecomeActive() {
    networkMonitor = NetworkMonitor()
    networkMonitor?.startMonitoring()
}

@objc func appMovedToBackground() {
    
    networkMonitor?.stopMonitoring()
    networkMonitor = nil
}

@objc private func listeningNetworkConnection() {
    DispatchQueue.main.async { [weak self] in
        self?.updateUI()
    }
}

private func updateUI() {
    
    guard let networkMonitor = networkMonitor else {
        return
    }
    
    if networkMonitor.isConnected{
        print("connected")
        networkConnectivityView.configure(with: "Connected")
    } else {
        print("Not connected")
        networkConnectivityView.configure(with: "Not Connected")
    }
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    
    networkConnectivityView.frame = CGRect(x: 0,
                                           y: 0,
                                           width: view.frame.size.width,
                                           height: 50)
    networkConnectivityView.center = view.center
}
}

这工作正常,但问题是每当我想在其他视图控制器中使用它时,我必须复制代码以在 appDidBecomeActive 中再次分配NetworkMonitorappMovedToBackground中使其为零。

所以请帮助我改进我的方法,这样我只需要在视图控制器中调用startMonitoring

4

1 回答 1

0

你考虑过方法UIApplicationDelegate吗?也可能是一个好主意,让你的单身人士和电话,并在各自的方法applicationWillResignActive(_:)applicationWillEnterForeground(_:)NetworkMonitorstopMonitoring()startMonitoring()UIApplicationDelegate

于 2021-03-11T00:25:58.183 回答