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
}
}
}
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