6

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?

foxtrotuniform6969
  • 3,527
  • 7
  • 28
  • 54
  • One option might be to programmatically change the volume the opposite direction that the user is so that the events keep firing the whole duration of the button press, and then use a timer to set a timeout that fires when the volume change event has not fired in X milliseconds. However, that feels very dirty... – foxtrotuniform6969 Jan 20 '20 at 17:25
  • Did you try: https://stackoverflow.com/a/28474014/12555191 – DrewG23 Jan 20 '20 at 17:33
  • @DrewG23 Trying to get that working now, but isn't that pretty much what I'm doing already, just with `NotificationCenter`? – foxtrotuniform6969 Jan 20 '20 at 17:50

1 Answers1

2

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

Marko
  • 2,778
  • 2
  • 10
  • 19
  • Yes, I should have added that to my question. I was hoping there might be some built-in mechanism, as I'm not too keen on relying on pods that haven't been touched in two (JPSVolumeButtonHandler) and three (PhysicalButton) years. I may have to integrate this code by hand. – foxtrotuniform6969 Jan 27 '20 at 18:02
  • I'm also really not sure where these classes handle releasing the volume button, I just see hooks for volume up pressed and volume down pressed, unless I'm misreading? https://github.com/jpsim/JPSVolumeButtonHandler/blob/master/JPSVolumeButtonHandler/JPSVolumeButtonHandler.m – foxtrotuniform6969 Jan 29 '20 at 20:38