Last active
August 31, 2017 11:28
-
-
Save hashaam/5ad24f69e0f3caef10c79bda80b794d0 to your computer and use it in GitHub Desktop.
Handle Remote Control Commands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://hashaam.com/2017/07/19/handle-remote-control-commands/ | |
import UIKit | |
import MediaPlayer | |
class ViewController: UIViewController { | |
var player: AVPlayer? | |
func setupRemoteCommandCenter(enable: Bool) { | |
let remoteCommandCenter = MPRemoteCommandCenter.shared() | |
if enable { | |
remoteCommandCenter.pauseCommand.addTarget(self, action: #selector(remoteCommandCenterPauseCommandHandler)) | |
remoteCommandCenter.playCommand.addTarget(self, action: #selector(remoteCommandCenterPlayCommandHandler)) | |
remoteCommandCenter.stopCommand.addTarget(self, action: #selector(remoteCommandCenterStopCommandHandler)) | |
remoteCommandCenter.togglePlayPauseCommand.addTarget(self, action: #selector(remoteCommandCenterPlayPauseCommandHandler)) | |
} else { | |
remoteCommandCenter.pauseCommand.removeTarget(self, action: #selector(remoteCommandCenterPauseCommandHandler)) | |
remoteCommandCenter.playCommand.removeTarget(self, action: #selector(remoteCommandCenterPlayCommandHandler)) | |
remoteCommandCenter.stopCommand.removeTarget(self, action: #selector(remoteCommandCenterStopCommandHandler)) | |
remoteCommandCenter.togglePlayPauseCommand.removeTarget(self, action: #selector(remoteCommandCenterPlayPauseCommandHandler)) | |
} | |
remoteCommandCenter.pauseCommand.isEnabled = enable | |
remoteCommandCenter.playCommand.isEnabled = enable | |
remoteCommandCenter.stopCommand.isEnabled = enable | |
remoteCommandCenter.togglePlayPauseCommand.isEnabled = enable | |
} | |
deinit { | |
setupRemoteCommandCenter(enable: false) | |
} | |
func remoteCommandCenterPauseCommandHandler() { | |
// handle pause | |
player?.pause() | |
} | |
func remoteCommandCenterPlayCommandHandler() { | |
// handle play | |
player?.play() | |
} | |
func remoteCommandCenterStopCommandHandler() { | |
// handle stop | |
player?.pause() | |
} | |
func remoteCommandCenterPlayPauseCommandHandler() { | |
// handle play pause | |
if player?.rate == 0.0 { | |
player?.play() | |
} else { | |
player?.pause() | |
} | |
} | |
func setupPlayer() { | |
let streamURL = URL(string: "https://audio.stream.m3u8")! | |
self.player = AVPlayer(url: streamURL) | |
self.player?.play() | |
} | |
@IBAction func playButtonHandler(btn: UIButton) { | |
setupRemoteCommandCenter(enable: true) | |
setupPlayer() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment