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?
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)]
i've the same issues. I tried to use also solutions proposed by other users, but I still can't perceive the click of the button tv remote app / pause. I tried with this code but without result.
i'm using xcode 10 and swift 5
override func viewDidLoad() {
super.viewDidLoad()
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(playPauseButtonPressed))
tapRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.playPause.rawValue)];
tapRecognizer.allowedTouchTypes = [NSNumber(value: UITouch.TouchType.indirect.rawValue)]
view.addGestureRecognizer(tapRecognizer)
UIApplication.shared.beginReceivingRemoteControlEvents()
}
@objc func playPauseButtonPressed(_ sender: AnyObject) {
print("PRESSED")
}
override func remoteControlReceived(with event: UIEvent?) {
print("EVENT")
}
override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
for press in presses {
if(press.type == UIPress.PressType.playPause) {
print("qui")
} else {
super.pressesEnded(presses, with: event)
print("qua")
}
}
}