I would like to perform one action when the user presses either volume button, and another when they stop pressing it, similar to what I can do by overriding touchesBegan()
and touchesEnded
.
I'm aware I can list to the volume level on change like so:
NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
@objc func volumeChanged(notification: NSNotification) {
if let userInfo = notification.userInfo {
if let volumeChangeType = userInfo["AVSystemController_AudioVolumeChangeReasonNotificationParameter"] as? String {
// do something here, such as a switch based off of "volumeChangeType"
}
}
}
However, once the user has turned the volume up or down all the way, events are no longer fired. Also, no event is fired when the user stops pressing the button. This makes sense, because I'm actually listening to a volume change event, not a volume button press event.
Is there a way to listen to physical button presses in iOS?
Take a look at this GitHub Repo which looks like it provides everything that you're asking for.
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