iPhone检测音量键按下。

我需要检测用户何时按下硬件音量键,(App Store安全方法)我已经尝试了一些没有运气的东西。 你知道如何实现这样的function吗? 目前我正在注册通知,但他们似乎并没有被调用。 这是我的代码:

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会话:

 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]; 

您将需要存储音量,并将其与通知中获得的先前值进行比较,以了解按下哪个button。

当用户按下音量键时,此解决scheme仍将调整系统音量,并显示音量叠加。 如果要避免更改系统音量并显示叠加层(实际上完全重新调整音量键), 请参阅此答案