微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

后台监听AVAudioSession路由变化

如何解决后台监听AVAudioSession路由变化

在我的应用程序中,我希望在用户连接某些无线音频播放器(耳机、扬声器等)时收到通知...

除了在连接时写入日志之外,该应用程序目前实际上什么都不做。现在,虽然应用程序在前台,但我正确地看到了所有日志,但是一旦我进入主屏幕,并尝试连接/断开某些东西,我就不再看到日志了。应用在后台时是否可以收到通知

我也想收到通知,即使应用程序已完全关闭 - 我认为这是不可能的。 (如果是这样,那么即使关闭了 WhatsApp 等应用程序,它们如何仍能收到通知)。

这是我创建通知的方式:

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        setupNotifications()
        
        return true
    }

func setupNotifications() {
        
        print("AppDeleagte: setupNotification")
        
        NotificationCenter.default.addobserver(self,selector: #selector(handleRouteChange),name: AVAudioSession.routeChangeNotification,object: AVAudioSession.sharedInstance())
    }
    
    @objc func handleRouteChange(notification: NSNotification) {
        guard let userInfo = notification.userInfo,let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {
                return
        }
        
        switch reason {
        
        case .newDeviceAvailable:
            let session = AVAudioSession.sharedInstance()
            print("AppDelegate: handleRouteChange () --> new device available")
            for output in session.currentRoute.outputs {
//                headphonesConnected = true
                print("output port type = ",output.portType," output port name = ",output.portName)
            }
        case .oldDeviceUnavailable:
            print("AppDelegate: handleRouteChange () --> old device unavailable")
            if let prevIoUsRoute =
                userInfo[AVAudioSessionRouteChangePrevIoUsRouteKey] as? AVAudioSessionRouteDescription {
                for output in prevIoUsRoute.outputs  {
//                    headphonesConnected = false
                }
            }
        default: ()
        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。