我需要检测用户何时按下硬件音量键,(App Store 安全方法)我尝试了很多方法,但都没有成功。你知道如何实现这样的功能吗?目前我正在注册通知,但他们似乎没有收到通知。这是我的代码:
AudioSessionInitialize(NULL, NULL, NULL, NULL);
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(volumeChanged:)
name:@"AVSystemController_SystemVolumeDidChangeNotification"
object:nil];
接收方方法是:
-(void)volumeChanged:(NSNotification *)notification{
NSLog(@"YAY, VOLUME WAS CHANGED");}
如有任何提示,我们将不胜感激。
最佳答案
您需要在通知触发之前启动 Audio Session :
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AudioSessionSetActive(true);
现在您可以订阅通知了:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(volumeChanged:)
name:@"AVSystemController_SystemVolumeDidChangeNotification"
object:nil];
获取音量:
float volume = [[[notification userInfo]
objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"]
floatValue];
您需要存储音量并将其与之前从通知中获得的值进行比较,以了解按下了哪个按钮。
当用户按下音量键时,该解决方案仍会调整系统音量,并显示音量叠加层。如果你想避免改变系统音量和显示覆盖(本质上完全改变音量键的用途),see this answer
关于iPhone 检测音量键按下。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7528443/