I'm trying to monitor the notifications for AVAudioSessionRouteChange
while in background.
NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange(_:)), name: NSNotification.Name.AVAudioSessionRouteChange, object: nil)
func handleRouteChange(_ notification: Notification) {
guard
let userInfo = notification.userInfo,
let reasonRaw = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber,
let reason = AVAudioSessionRouteChangeReason(rawValue: reasonRaw.uintValue)
else { fatalError("Strange... could not get routeChange") }
switch reason {
case .oldDeviceUnavailable:
print("oldDeviceUnavailable")
case .newDeviceAvailable:
print("newDeviceAvailable")
case .routeConfigurationChange:
print("routeConfigurationChange")
case .categoryChange:
print("categoryChange")
default:
print("not handling reason")
}
}
Console:
newDeviceAvailable
oldDeviceUnavailable
newDeviceAvailable
oldDeviceUnavailable
newDeviceAvailable
oldDeviceUnavailable
newDeviceAvailable
routeConfigurationChange
oldDeviceUnavailable
newDeviceAvailable
All I do is plug/unplug the headphones, and I get the above log.
While the app is in foreground, the print statements are logged immediately. But, if the app is pushed to background, they aren't logged. But, as I bring the app to foreground, I receive all the notifications.
So,I'm wondering if its possible to monitor the notifications while the app is in background?