IOS网络状态变化监听

1|0IOS网络状态变化监听

使用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)


__EOF__

本文作者R1cardo
本文链接https://www.cnblogs.com/r1cardo/p/17289358.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   R1cardo  阅读(875)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
点击右上角即可分享
微信分享提示