detect MPMusicPlayerController notifications in background
Asked Answered
H

2

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?

Hinder answered 14/10, 2014 at 22:8 Comment(1)
Did you get any further here?Omentum
O
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.

Oversubtle answered 11/8, 2016 at 19:10 Comment(2)
in the background too?Demolish
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.Oversubtle
F
0

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

enter image description here

Faldstool answered 26/3, 2021 at 7:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.