aaaav
aaaav

Reputation: 161

Listen to volume button presses the correct way (iOS 15)

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?

Upvotes: 14

Views: 2827

Answers (2)

devabhishekpal
devabhishekpal

Reputation: 115

I think this is duplicate of Detect hardware volume button press when volume not changed.

They simply import MediaPlayer And then:

let volumeView = MPVolumeView(frame: CGRect.zero)
self.view.addSubview(volumeView)
NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)

@objc func volumeChanged(_ notification: NSNotification) {
 if let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"] as? Float {
     print("volume: \(volume)")
 }
}

This will output:


volume: 0.8125
volume: 0.875
volume: 0.9375
volume: 1.0
volume: 1.0
volume: 1.0
volume: 1.0

Remember to import MediaPlayer.

Also Jayesh Patel’s answer is short and accurate, so you may use that too.

Upvotes: 1

Jayesh Patel
Jayesh Patel

Reputation: 1104

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

Upvotes: 1

Related Questions