问题
I have an AVAudioPlayer in my app and I am adding a function where the user can press the Play/Pause button on the remote to Play/Pause the AVAudioPlayer. I have this code in my App Delegate:
func initializePlayButtonRecognition() {
addPlayButtonRecognizer(#selector(AppDelegate.handlePlayButton(_:)))
}
func addPlayButtonRecognizer(_ selector: Selector) {
let playButtonRecognizer = UITapGestureRecognizer(target: self, action:selector)
playButtonRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.playPause.rawValue as Int)]
self.window?.addGestureRecognizer(playButtonRecognizer)
}
func handlePlayButton(_ sender: AnyObject) {
if audioPlayer.isPlaying {
audioPlayer.pause() {
} else {
audioPlayer.play()
}
}
}
The AVAudioPlayer's name is an audio player. I have that stated in the code, but the App Delegate does not have a reference to the AVAudioPlayer from the PlayerViewController. How do I do this?
回答1:
Your code looks correct. Just a missing detail that could explain why it does not work as expected... in tvOS, apart from setting allowedPressTypes
it is also needed to define allowedTouchTypes
as indirect:
playButtonRecognizer.allowedTouchTypes = [NSNumber(value: UITouchType.indirect.rawValue)]
来源:https://stackoverflow.com/questions/43428807/add-action-to-apple-tv-remote-play-pause-button