iDev_01

Swift 耳机插拔控制类型转换错误

2019-01-07

现象

我们判断耳机拔出需要订阅一个 AVAudioSession.routeChangeNotification通知

1
NotificationCenter.default.addObserver(self, selector: #selector(Test.handleRouteChange(notification:)), name: AVAudioSession.routeChangeNotification, object: AVAudioSession.sharedInstance())

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@objc func handleRouteChange(notification: Notification) -> Void {
if let userInfo = notification.userInfo,
let changeResonNumber = userInfo[AVAudioSessionRouteChangeReasonKey] as? AVAudioSession.RouteChangeReason ,
let changeResonDescription = userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? [AVAudioSessionPortDescription] {
print(changeReson)
switch changeReson {
case .oldDeviceUnavailable:
if changeResonDescription[1].portType == AVAudioSession.Port.headphones {
self.player.pause()
} else {
self.player.resume()
}
default:
self.player.pause()
}
}
}

方法 handleRouteChange(notification:) 中的第二行报错

原因

userInfo[AVAudioSessionRouteChangeReasonKey]返回的是NSNumber,而不是AVAudioSession.RouteChangeReason。类型转换错误必然导致不会运行if中的语句。

解决方案

既然拿到的是NSNumber类型,下面有两种方案:

  • 为了减少不必要的类型转换,直接由NSNumber得到UInt(采用注释的方法使代码逻辑更清晰)
  • 为了代码语义清楚,先由NSNumber得到UInt,再构造AVAudioSession.RouteChangeReason

最后使用switch/if语句写后续的判断与逻辑。

使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏

扫描二维码,分享此文章