an alternative title is "Why AVSystemController_AudioVolumeNotificationParameter notification event never get triggered?"
The goal is to monitor the volume change event and its value. Followed the guide at detect up volume change swift.
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
need to be called first.
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.