AudioPlayer and lockscreen/control center control Swift [closed]
Asked Answered
O

1

5

I'm new on Swift. I write because I want to ask a question. Me and my friend we are developing an audio player, but we have a problem. The player also works in background and remote controls from the lockscreen and the control center work, but if music is interrupted by one of these two controls, the play/pause button of our player is not updated with the correct icon. My question is, how can I make it clear to the player that the music was starting/stopping by one of the remote controls and the player to act accordingly, changing the icon of play/pause button? thanks a lot, I hope I was clear.

Ontologism answered 20/3, 2017 at 6:46 Comment(0)
S
16

You need to use the MPRemoteCommandCenter to do this. For example in your viewControllers viewDidLoad() you can add this:

override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.shared.beginReceivingRemoteControlEvents()
    let commandCenter = MPRemoteCommandCenter.shared()

    commandCenter.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
        //Update your button here for the pause command
        return .success
    }

    commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
        //Update your button here for the play command
        return .success
    }

}

Just change the comments I have included to update your buttons UI. You will also need to import MediaPlayer and MediaPlayer.framework if you have not done so already.

Seigneury answered 20/3, 2017 at 7:31 Comment(3)
Works perfectly! ThanksOntologism
You don't need to call UIApplication.shared.beginReceivingRemoteControlEvents() if you are already using MPRemoteCommandCenter, see developer.apple.com/documentation/uikit/uiapplication/… for more details.Pfeifer
@totiG, it is worked for me. But after press the pause button in locked screen control panel, then reopen the locked screen, the control panel is not showing again. What is the reason, is there some parameter to set flag here?Burnet

© 2022 - 2024 — McMap. All rights reserved.