Swift 4.1中如何在AppDelegate的didFinishLaunchingWithOptions配置全局网络检测
全局网络状态检测的AppDelegate配置方案
嘿,我来帮你搞定这个全局网络检测的配置!既然你已经备齐了ReachabilityHandler.swift、extension_UIApplication.swift和Reachability.swift这些网络相关文件,那在AppDelegate.swift的application(_:didFinishLaunchingWithOptions:)方法里只需要几步就能实现全页面的网络状态监听啦:
第一步:在AppDelegate中持有Reachability实例
首先得在AppDelegate类里加一个属性来持有Reachability对象,不然监听会因为对象被释放而失效:
class AppDelegate: UIResponder, UIApplicationDelegate { // 持有Reachability实例,避免被ARC释放 private var reachability: Reachability? // ... 其他已有代码 }
第二步:在启动方法中初始化并启动监听
接下来在application(_:didFinishLaunchingWithOptions:)里完成初始化、回调设置和启动监听的逻辑:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 初始化Reachability并配置监听 do { self.reachability = try Reachability() // 网络可达时的回调 reachability?.whenReachable = { reachability in DispatchQueue.main.async { // 通过通知中心广播网络可达事件,让所有页面能收到通知 NotificationCenter.default.post( name: NSNotification.Name("NetworkStatusReachable"), object: reachability.connection // 可以把当前网络类型(WiFi/蜂窝)传过去 ) print("网络已连接:\(reachability.connection.description)") } } // 网络不可达时的回调 reachability?.whenUnreachable = { _ in DispatchQueue.main.async { NotificationCenter.default.post( name: NSNotification.Name("NetworkStatusUnreachable"), object: nil ) print("网络已断开") } } // 启动网络监听 try reachability?.startNotifier() } catch { print("初始化Reachability失败:\(error.localizedDescription)") } return true }
第三步:在App终止时停止监听
为了避免内存泄漏,记得在App即将终止时停止监听:
func applicationWillTerminate(_ application: UIApplication) { reachability?.stopNotifier() }
额外优化:用ReachabilityHandler简化逻辑
如果你已经封装了ReachabilityHandler,可以直接用它来简化代码,让逻辑更集中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 启动全局网络监听,通过Handler统一处理状态变化 ReachabilityHandler.shared.startMonitoring { status in DispatchQueue.main.async { switch status { case .reachable(.wifi): NotificationCenter.default.post(name: .networkReachableViaWiFi, object: nil) case .reachable(.cellular): NotificationCenter.default.post(name: .networkReachableViaCellular, object: nil) case .unreachable: NotificationCenter.default.post(name: .networkUnreachable, object: nil) } } } return true }
各个页面如何接收状态通知?
在需要监听网络状态的ViewController里,只需要监听对应的通知即可:
class YourViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // 注册网络状态通知 NotificationCenter.default.addObserver( self, selector: #selector(handleNetworkStatusChange(_:)), name: NSNotification.Name("NetworkStatusReachable"), object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(handleNetworkUnreachable), name: NSNotification.Name("NetworkStatusUnreachable"), object: nil ) } // 处理网络可达事件 @objc private func handleNetworkStatusChange(_ notification: Notification) { if let connection = notification.object as? Reachability.Connection { // 根据网络类型更新UI或业务逻辑 print("当前网络:\(connection.description)") } } // 处理网络不可达事件 @objc private func handleNetworkUnreachable() { // 显示无网络提示,比如弹出Alert或者更新页面状态 print("当前无网络连接") } // 记得在销毁时移除通知监听 deinit { NotificationCenter.default.removeObserver(self) } }
内容的提问来源于stack exchange,提问作者mannyCalavera
相关产品推荐
相关产品推荐

