2016-01-21 61 views
5

我正在构建一个音乐播放器应用程序,并且一切工作正常。到目前为止,我一直在使用系统音乐播放器,但现在想切换到使用应用程序音乐播放器,而这正是我遇到问题的地方 - 对于我的生活,我无法弄清楚如何让我的播放/暂停回调将从iOS控制中心调用。下面是我用我的主视图控制器代码:使用MPRemoteCommandCenter时不会呼叫播放/暂停回叫

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.musicPlayer = MPMusicPlayerController.applicationMusicPlayer() 

    self.registerForMediaPlayerNotifications() 
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents() 

    let commandCenter = MPRemoteCommandCenter.sharedCommandCenter() 

    commandCenter.previousTrackCommand.enabled = false 
    commandCenter.previousTrackCommand.addTarget(self, action: "previousTrack") 
    commandCenter.nextTrackCommand.enabled = false 
    commandCenter.nextTrackCommand.addTarget(self, action: "nextTrack") 
    commandCenter.togglePlayPauseCommand.enabled = true 
    commandCenter.togglePlayPauseCommand.addTarget(self, action: "playOrPauseMusic") 
    commandCenter.pauseCommand.addTarget(self, action: "playOrPauseMusic") 
    commandCenter.pauseCommand.enabled = true 
    commandCenter.playCommand.addTarget(self, action: "playOrPauseMusic") 
    commandCenter.playCommand.enabled = true 

    [...] 
} 


func previousTrack() { 
} 

func nextTrack() { 
} 

func playOrPauseMusic() { 
    print("playOrPause") 
} 
+0

我能想到的唯一的事情就是当回调来的时候你的对象不再存在了。你把物体存放在什么地方? – fishinear

+0

你的意思是commandCenter对象?不,我不会在任何地方存储,因为我认为这将是一些全局共享实例,我只需要设置目标/启用/禁用等参考。我可以试一试虽然... – dflachbart

+0

不,我的意思是self,包含此代码的对象。在它的'dealloc'中放一个断点,看看它是否被清理干净。 – fishinear

回答

1

尝试增加Required background modes到像这样的Info.plist:

Info.plist screenshot

+0

是的,我已经尝试过,没有作出改变... – dflachbart

-3

发生在viewDidApper你的代码。

+0

,这并没有为我工作。它适合你吗? – evenodd

3

我有这个相同的问题,并注意到togglePlayPauseCommand的回调没有被调用,但previousTrackCommand是。所以经过一些实验后,我通过删除togglePlayPauseCommand而取得了这项工作,取而代之的是个别地实现了playCommandpauseCommand的内联回调 - 请注意,使用自定义选择器不起作用,它们必须是内联回调。

let commandCenter = MPRemoteCommandCenter.shared() 

commandCenter.playCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in 
    moviePlayer.prepareToPlay() 
    moviePlayer.play() 
    return MPRemoteCommandHandlerStatus.success 
} 

commandCenter.pauseCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in 
    moviePlayer.pause() 
    return MPRemoteCommandHandlerStatus.success 
}