1

我正在做这个测试应用程序,我想在 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);
    }
}
4

2 回答 2

1

请参阅这篇文章,您在后台的选项非常有限:

StackOverFlow 帖子

而关于该状态的 Apple Docs 是不可能的: Apple Documentation on Background states

于 2012-10-06T15:25:46.963 回答
-1

进入后台时一定要移除观察者:

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

进入前台时再次添加。

于 2013-07-16T13:40:55.037 回答