SystemVolumeDidChangeNotification永远不会在iOS 14上触发

问题描述:

目标是监视音量更改事件及其值.遵循检测音量变化迅速的指南.

The goal is to monitor the volume change event and its value. Followed the guide at detect up volume change swift.

在iOS 14. *上,当我尝试观察音量变化事件时,似乎在音量变化后从未触发该事件.

On iOS 14.* when I try to observe volume change event, the event seems to never get triggered after volume change.

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

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

在视图消失后,不要忘记删除观察者.

Do not forget to remove the observer after the view disappeared.