IOS网络状态变化监听

发布时间 2023-04-05 14:16:43作者: R1cardo

IOS网络状态变化监听

使用Alamofire库的NetworkReachabilityManager

一共有三种状态

/// It is unknown whether the network is reachable.
case unknown
/// The network is not reachable.
case notReachable
/// The network is reachable on the associated `ConnectionType`.
case reachable(ConnectionType)

分别是

  • 未知
  • 未连接
  • 已连接

其中已连接又分为两种

/// The connection type is either over Ethernet or WiFi.
case ethernetOrWiFi
/// The connection type is a cellular connection.
case cellular

分别是

  • 以太网或wifi
  • 蜂窝网络

开始监听

reachability?.startListening(onUpdatePerforming: { status in
            switch status {
            case .notReachable:
                print("无网络")
                self.isWifiOn = false
                self.isCellarOn = false
            case .unknown:
                print("未知")
                self.isWifiOn = false
                self.isCellarOn = false
            case .reachable(let type):
                self.isWifiOn = type == .ethernetOrWiFi
                self.isCellarOn = type == .cellular
            }
            NotificationCenter.default.post(name: deviceNetworkNotification, object: nil, userInfo: ["wifi": self.isWifiOn, "cellar": self.isCellarOn])
        })

监听到网络改变时发送全局通知

需要接收通知的地方添加监听

NotificationCenter.default.addObserver(self, selector: #selector(onNetworkChanged(noti:)), name: deviceNetworkNotification, object: nil)