Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Listen to physical button up/down events on iOS device

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?

like image 706
foxtrotuniform6969 Avatar asked Jan 20 '20 17:01

foxtrotuniform6969


1 Answers

Take a look at this GitHub Repo which looks like it provides everything that you're asking for.

like image 72
Marko Avatar answered Nov 10 '22 04:11

Marko