在我的应用程序中,用户可以在他按下屏幕上的 UIButton 时对他的麦克风说一个命令(当他再次按下它时它会停止监听),然后它会执行一些代码(-> 这有效)。
当用户按下他的耳机上的播放/暂停按钮而不是屏幕上的 UIButton(并且他在这个 VC 上)时,我想做同样的事情。
我已经看过很多关于如何使用 iPhone 耳机的播放/暂停按钮的教程,但我无法让它们为我工作。
我没有设法抓住按钮按下,它只是继续播放/暂停我的图书馆中的音乐。
目前我有 UIButton 的 VC,这是我添加的代码,但我从未进入 remoteControlReceived 函数:
override var canBecomeFirstResponder : Bool {
return true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.becomeFirstResponder()
UIApplication.shared.beginReceivingRemoteControlEvents()
}
override func remoteControlReceived(with event: UIEvent?) {
if (event?.type == UIEventType.remoteControl) {
if event?.subtype == UIEventSubtype.remoteControlTogglePlayPause {
//execute the code ...
}
}
}