Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Detect Volume Button Press NOT volume change events

Tags:

ios

swift

Is there a way to specifically detect the button presses, NOT the volume change events. I tried following these two posts, but they detect volume change NOT button presses:

Cleanest way of capturing volume up/down button press on iOS8

swift detect volume button press

The reason I cannot use these two events, is because my app automatically adjusts the volume during certain events. When the app does this, it is not the same event as when the user manually presses the volume buttons.

like image 921
Pavel Avatar asked Oct 01 '16 21:10

Pavel


1 Answers

So what I'd do is subscribe to the notification like they do in the questions you linked and then add a variable named say programmaticVolumeChange. When you change the volume programmatically set the variable to true, then in your function observeValueForKeyPath, if the variable is true don't cancel the alarm (and naturally set it to false after). That way when the user presses the volume buttons you know it wasn't your code. Maybe test the amount of time between a programmatic volume change and the function call but I think that would be fine.

Eg

var programmaticVolumeChange = false

func changeVolumeProgramatically() {

    programmaticVolumeChange = true
    //change volume programmatically after

}

override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject,
change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {

    if keyPath == "outputVolume"{

        if programmaticVolumeChange {

            programmaticVolumeChange = false

        } else {

            //handle logic for user volume button press

        }

    }

}
like image 165
Olivier Wilkinson Avatar answered Sep 22 '22 01:09

Olivier Wilkinson