12

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?

jlgaustin
  • 253
  • 2
  • 10

2 Answers2

1

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.

Eric Hodgins
  • 546
  • 1
  • 9
  • 14
  • in the background too? – evenodd Aug 16 '16 at 20:34
  • I did more testing and unfortunately once the app is suspended it won't execute code until active again. From what I've read MPMusicPlayer notifications will not work in the background. Now AVPlayer executes code in the background and works with iPod library items but it's more complicated to setup. – Eric Hodgins Aug 17 '16 at 04:04
0

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

enter image description here

Van
  • 1,225
  • 10
  • 18