简体   繁体   English

Swift:检测音量按钮按NOT音量改变事件

[英]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 在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. 所以我要做的就是订阅通知,就像他们在你链接的问题中做的那样,然后添加一个名为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). 当您以编程方式将变量设置为true时,然后在函数observeValueForKeyPath中,如果变量为true,则不取消警报(并在之后自然将其设置为false)。 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

        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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