I have used
NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
in the past to listen to volume control changes however this no longer works in iOS 15.
This alternative code below only works well if you don't care about a user pressing the volume up when at max volume. However, I do want to know every time the button is pressed.
AVAudioSession.sharedInstance().addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
What is the correct way to listen to the user pressing the volume control button even when the volume is at its max/min?
Make Sure Your iPhone's Volume Buttons Are Enabled To check this, head to Settings > Sounds & Haptics and enable Change with Buttons. If this isn't enabled, this is why your volume buttons aren't working. If it's already enabled, proceed to the next fix.
If the buttons don't change anything, go to Settings > Sounds & Haptics, then check that Change with Buttons is turned on. Alternatively, you can alter the volume via the Control Center by swiping down from the top-right of your screen (iPhone X and later).
You need to use mediaplayer liabrary for it.
just import MediaPlayer
let volumeView = MPVolumeView(frame: CGRect.zero)
self.view.addSubview(volumeView)
You will get event of every press regardless of volume level
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With