ReachabilitySwift通知集成报错:无法识别reachabilityChanged方法
解决ReachabilitySwift通知Selector未识别的问题
这个问题我之前也碰到过,核心原因是Swift方法默认不暴露给Objective-C运行时,而NotificationCenter的addObserver依赖Objective-C的Selector机制,再加上你的Selector签名和方法定义不匹配,才导致了"未解析的标识符"错误。下面是具体的修复步骤:
1. 给监听方法添加@objc修饰符
Swift中,只有标记了@objc的方法才能被Objective-C运行时识别,所以你需要给reachabilityChanged方法加上这个修饰符:
@objc func reachabilityChanged(note: Notification) { let reachability = note.object as! Reachability switch reachability.connection { case .wifi: print("Reachable via WiFi") case .cellular: print("Reachable via Cellular") case .none: print("Network not reachable") } }
2. 修正Selector的签名匹配
你的Selector写的是#selector(reachabilityChanged(_:)),但方法定义是reachabilityChanged(note:),签名不匹配。有两种修正方式:
- 方式一:保持方法参数名,Selector写成带参数名的形式:
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: centralreachability)
- 方式二:修改方法参数为下划线,匹配原Selector写法:
@objc func reachabilityChanged(_ note: Notification) { // 方法内容不变 } // 此时Selector用#selector(reachabilityChanged(_:))就没问题了
3. 修复Reachability实例的可选性问题
你定义的let centralreachability = Reachability(),如果Reachability的初始化方法是可失败的(比如init?()),这里应该改成可选类型,避免后续可选链的不必要使用:
var centralreachability: Reachability? = Reachability()
完整修正后的代码片段
class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? struct Constants { public static let googleApi = "xxx" } var centralreachability: Reachability? = Reachability() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // 修正Selector签名 NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: centralreachability) do{ try centralreachability?.startNotifier() } catch{ print("could not start reachability notifier") } NetworkActivityIndicatorManager.shared.isEnabled = true return true } // 添加@objc修饰符 @objc func reachabilityChanged(note: Notification) { guard let reachability = note.object as? Reachability else { return } switch reachability.connection { case .wifi: print("Reachable via WiFi") case .cellular: print("Reachable via Cellular") case .none: print("Network not reachable") } } // ... rest of AppDelegate }
另外,建议在deinit方法中移除通知观察者,避免内存泄漏:
deinit { NotificationCenter.default.removeObserver(self) centralreachability?.stopNotifier() }
内容的提问来源于stack exchange,提问作者MW_DEVEL
相关产品推荐
相关产品推荐

