Why is my app not responding to remote control events?

958 Views Asked by At

I'm making an app that plays an audio stream on the background when the device is locked. I want the app to respond to the media controls on the lock screen. I followed this answer but for some reason I can't make my app respond to these controls. This is the code I have on my View Controller

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    UIApplication.shared.beginReceivingRemoteControlEvents()
    becomeFirstResponder()
}

override var canBecomeFirstResponder: Bool {
    return true
}

override func remoteControlReceived(with event: UIEvent?) {
    guard let event = event else { return }
    if event.type == .remoteControl {
        switch event.subtype {
        case .remoteControlTogglePlayPause:
            if player.rate == 0 {
                player.pause()
            } else {
                player.play()
            }
        case .remoteControlPlay:
            player.play()
            break

        case .remoteControlPause:
            player.pause()
            break

        default:
            break
        }
    }
}`

Any guidance on what I'm doing wrong will be really appreciated!

0

There are 0 best solutions below