【问题标题】:SystemVolumeDidChangeNotification never get triggered on iOS 14SystemVolumeDidChangeNotification 永远不会在 iOS 14 上触发
【发布时间】:2020-11-02 06:05:30
【问题描述】:

另一个标题是“为什么 AVSystemController_AudioVolumeNotificationParameter 通知事件永远不会被触发?”

目标是监控音量变化事件及其值。按照detect up volume change swift 的指南进行操作。

在 iOS 14.* 上,当我尝试观察音量变化事件时,该事件似乎在音量变化后永远不会被触发。

import MediaPlayer

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(volumeChange(_:)), name: Notification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
}

@objc func volumeChange(_ notification: NSNotification) {
    let userInfo = notification.userInfo!
    let volume = userInfo["AVSystemController_AudioVolumeNotificationParameter"] as! Double

    print("volume:\(volume)")
}

【问题讨论】:

    标签: ios swift nsnotificationcenter ios14


    【解决方案1】:

    需要先调用beginReceivingRemoteControlEvents

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    
        UIApplication.shared.beginReceivingRemoteControlEvents() // <- THIS LINE
    
        NotificationCenter.default.addObserver(self, selector: #selector(volumeChange(_:)), name: Notification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
    }
    

    在视图消失后不要忘记移除观察者。

    【讨论】:

    • 谢谢,我想知道为什么我们在 iOS 14.1 之前不需要使用它。
    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 2016-10-29
    • 2014-05-15
    • 1970-01-01
    • 2021-05-22
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多