如何在后台接收MPMusicPlayerControllerNowPlayingItemDidChangeNotification?

时间:2012-10-06 15:15:16

标签: iphone objective-c ios

我正在做这个测试应用程序,我希望在iPod更改正在播放的项目(歌曲)时收到通知,当应用程序处于前台时测试工作正常但是一旦应用程序进入后台它停止获得通知,这是可以的,当我再次点击应用程序(来到前台)时我会根据应用程序在后台的所有时间获得所有通知,但每次我得到相同的歌曲信息,那么如何我可以为每个通知获取正确的歌曲信息吗?

这是我在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 个答案:

答案 0 :(得分:1)

看到这篇文章,您在后台的选项非常有限:

StackOverFlow Post

关于该州的Apple Docs实际上并不可能: Apple Documentation on Background states

答案 1 :(得分:-1)

请务必在进入后台时移除观察者:

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

进入前景时再次添加。