监控" AVAudioSessionRouteChange"背景通知?

时间:2016-10-25 13:30:07

标签: ios swift avaudiosession

我试图在后台监控AVAudioSessionRouteChange的通知。

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")
        }
    }

控制台:

newDeviceAvailable
oldDeviceUnavailable
newDeviceAvailable
oldDeviceUnavailable
newDeviceAvailable
oldDeviceUnavailable
newDeviceAvailable
routeConfigurationChange
oldDeviceUnavailable
newDeviceAvailable

我所做的只是插拔耳机,我得到了上面的日志。

当应用程序位于前台时,会立即记录打印语句。但是,如果应用程序被推送到后台,它们就不会被记录。但是,当我将应用程序带到前台时,我会收到所有通知。

所以,我想知道在应用程序处于后台时是否可以监控通知?

0 个答案:

没有答案