Search code examples
iphoneobjective-cbackgroundnsuserdefaultsmpmusicplayercontroller

How to save state of current MPMediaItem and respond to changed value when entering foreground


So I'm trying to develop a music game that uses the iPod music library. The user picks a song based on a prompt. Because I'm using [MPMusicPlayerController iPodMusicPlayer], it's possible the user changed the song in the iPod app before coming back to the app. If that's the case, I want it to call [musicPlayer stop]. Unfortunately, I can't figure out how to save the currently playing song and check it against the currently playing song when the app returns from background. Check the code below.

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *persistantID = [musicPlayer.nowPlayingItem valueForProperty:MPMediaItemPropertyPersistentID];
    [prefs setValue:persistantID forKey:@"NOWPLAYING_ID"];

}

And

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSString *persistantID = [prefs stringForKey:@"NOWPLAYING_ID"];
    if (persistantID == [musicPlayer.nowPlayingItem valueForProperty:MPMediaItemPropertyPersistentID]) {
    }
    else {
        [musicPlayer stop];
    }
    [prefs setValue:nil forKey:@"NOWPLAYING_ID"];

}

Can anyone give me a hand? Thanks so much.


Solution

  • - (void)applicationWillResignActive:(UIApplication *)application    {
        self.mediaItemSavedWhenAppSuspended = [musicPlayer nowPlayingItem];
    }
    
    - (void)applicationDidBecomeActive:(UIApplication *)application {
        MPMediaItem *nowPlayingItem = [musicPlayer nowPlayingItem];
        NSNumber *playingItem = [nowPlayingItem valueForProperty:MPMediaItemPropertyPersistentID];
        NSNumber *previousItem = [self.mediaItemSavedWhenAppSuspended valueForProperty:MPMediaItemPropertyPersistentID];
    
        if( [playingItem compare:previousItem] == NSOrderedSame )   {   //  same track still playing
       }