1
votes

I'm doing this test app where I want to receive notification when the iPod changes the now playing item (song), the test is working nice while app is in foreground but as soon as the app goes to the background it stop getting notifications which is OK, when I tap on the app again (comes to foreground) I get all notifications according to all the times the now playing changed while the app was in background but everytime I'm getting the same song information, so how can I get the correct song information for each notification?

This is the test I did, in the AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    MPMusicPlayerController *player = [MPMusicPlayerController iPodMusicPlayer];

    [notificationCenter addObserver:self
                           selector:@selector(nowPlayingItemChanged:)
                               name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
                             object:player];

    [player beginGeneratingPlaybackNotifications];

    return YES;
}

-(void) nowPlayingItemChanged:(NSNotification *)notification {
    MPMusicPlayerController *player = (MPMusicPlayerController *)notification.object;

    MPMediaItem *song = [player nowPlayingItem];

    if (song) {
        NSString *title = [song valueForProperty:MPMediaItemPropertyTitle];
        NSString *album = [song valueForProperty:MPMediaItemPropertyAlbumTitle];
        NSString *artist = [song valueForProperty:MPMediaItemPropertyArtist];
        NSString *playCount = [song valueForProperty:MPMediaItemPropertyPlayCount];

        NSLog(@"title: %@", title);
        NSLog(@"album: %@", album);
        NSLog(@"artist: %@", artist);
        NSLog(@"playCount: %@", playCount);
    }
}
2

2 Answers

1
votes

See this post your options in the background are pretty restricted:

StackOverFlow Post

And the Apple Docs regarding that state it is not really possible: Apple Documentation on Background states

-1
votes

Be sure to remove the observer when going into the background:

[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:musicPlayer];[player endGeneratingPlaybackNotifications];

Add it again when entering the foreground.