简体   繁体   中英

Swift: Detect Volume Button Press NOT volume change events

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.

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

        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM