问题描述
目标是监视音量更改事件及其值。遵循了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)")
}
解决方法
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)
}
视图消失后,不要忘记删除观察者。