1

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?

Shyam
  • 561
  • 5
  • 22
  • I know it's been a long time since, but did you solve this? – Keselme May 13 '21 at 07:45
  • @Keselme I haven't worked on it since.. Sorry, you might need to check as the APIs have been changed quite a bit over the years.. – Shyam May 14 '21 at 09:38

0 Answers0