现象
我们判断耳机拔出需要订阅一个 AVAudioSession.routeChangeNotification通知1
NotificationCenter.default.addObserver(self, selector: #selector(Test.handleRouteChange(notification:)), name: AVAudioSession.routeChangeNotification, object: AVAudioSession.sharedInstance())
1 | func handleRouteChange(notification: Notification) -> Void { |
方法 handleRouteChange(notification:) 中的第二行报错
原因
userInfo[AVAudioSessionRouteChangeReasonKey]返回的是NSNumber,而不是AVAudioSession.RouteChangeReason。类型转换错误必然导致不会运行if中的语句。
解决方案
既然拿到的是NSNumber类型,下面有两种方案:
- 为了减少不必要的类型转换,直接由
NSNumber得到UInt(采用注释的方法使代码逻辑更清晰) - 为了代码语义清楚,先由
NSNumber得到UInt,再构造AVAudioSession.RouteChangeReason
最后使用switch/if语句写后续的判断与逻辑。
赏
使用支付宝打赏
使用微信打赏
若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏
扫描二维码,分享此文章