在后台检测MPMusicPlayerController通知

jlg*_*tin 10 objective-c avfoundation mpmusicplayercontroller ios swift

我有一个用swift编写的音乐应用程序,我使用的是MPMusicPlayerController.systemMusicPlayer,也尝试过applicationMusicPlayer.

正如预期的那样,音乐在后台播放得很好

当我的应用程序在后台时,我需要播放状态更改通知,因此我的应用可以确定要播放的下一首歌曲.

我在viewDidLoad方法中有以下内容.如果我的应用程序在前台,我的方法"playbackChanged"会被调用所有正确的状态.

 NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "playbackChanged",
        name:MPMusicPlayerControllerPlaybackStateDidChangeNotification,
        object: MPMusicPlayerController.systemMusicPlayer()
   )
Run Code Online (Sandbox Code Playgroud)

如果我的应用程序在后台,我什么都得不到.我记得在iOS 7中使用现在已经在iOS 8中弃用的iPodMusicPlayer,我会在后台正确地收到这些通知.

任何想法都出错了?

Eri*_*ins 1

调用beginGeneratingPlaybackNotifications()MusicPlayer 似乎对我有用。

 MPMusicPlayerController.systemMusicPlayer().beginGeneratingPlaybackNotifications()
 NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "playbackChanged",
    name:MPMusicPlayerControllerPlaybackStateDidChangeNotification,
    object: MPMusicPlayerController.systemMusicPlayer()
 )
Run Code Online (Sandbox Code Playgroud)

更新:不幸的是 MPMusicPlayerNotifications 将无法在后台可靠地工作。