11
votes

I have a music app written in swift, I am using MPMusicPlayerController.systemMusicPlayer, also tried applicationMusicPlayer.

Music plays fine in the background as expected.

When my app is in the background I need playback state change notifications, so my app can determine next song to play.

I have the following in my viewDidLoad method. My method "playbackChanged" gets called with all the correct states if my application is in the foreground.

 NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "playbackChanged",
        name:MPMusicPlayerControllerPlaybackStateDidChangeNotification,
        object: MPMusicPlayerController.systemMusicPlayer()
   )

I get nothing if my app is in the background. I remember with iOS 7 and using the iPodMusicPlayer which is now deprecated in iOS 8, I would get these notifications in the background correctly.

Any ideas whats going wrong?

2
Did you get any further here? - newenglander

2 Answers

0
votes

Calling beginGeneratingPlaybackNotifications() on the MusicPlayer seemed to work for me.

 MPMusicPlayerController.systemMusicPlayer().beginGeneratingPlaybackNotifications()
 NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "playbackChanged",
    name:MPMusicPlayerControllerPlaybackStateDidChangeNotification,
    object: MPMusicPlayerController.systemMusicPlayer()
 )

UPDATE: Unfortunately MPMusicPlayerNotifications will not work reliably in the background.

0
votes

Have you added capabilities for audio for background modes option? Apple documentaion

enter image description here