【问题标题】:Refresh application state running on background刷新后台运行的应用程序状态
【发布时间】:2017-05-05 06:09:03
【问题描述】:

我有音乐播放器应用程序,当应用程序进入后台时,它会在锁定屏幕上显示音乐控制,就我而言,目前正在播放广播艺术家和歌曲。我使用以下内容:

- (void)applicationWillResignActive:(UIApplication *)application {
    [[PlayerManager sharedInstance] setupInfoForLockerScreen];
}

-(void)setupInfoForLockerScreen{

    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    NSString *songName = self.currentPlaylist.lastItem.track.song.length > 0 ? self.currentPlaylist.lastItem.track.song : @"";
    NSString *artistName = self.currentPlaylist.lastItem.track.artist.length > 0 ? self.currentPlaylist.lastItem.track.artist : @"";
    infoCenter.nowPlayingInfo = @{
                                  MPMediaItemPropertyTitle:     self.currentPlaylist.title,
                                  MPMediaItemPropertyArtist:    songName.length > 0 && artistName.length > 0 ? [NSString stringWithFormat:@"%@ - %@", songName, artistName] : @"",
                                  MPMediaItemPropertyPlaybackDuration: @(0)
                                  };
}

问题是,当数据更改并且下一首歌曲将在广播中播放时,我如何告诉我的应用程序自行刷新? applicationWillResignActive 我猜应用程序最初进入后台时只调用了一次。

【问题讨论】:

    标签: ios objective-c uiapplication


    【解决方案1】:

    MPMusicPlayerController 类有一些方法和事件可以帮助解决这个问题。

    首先你需要告诉你的应用程序监听 MPMusicPlayerControllerNowPlayingItemDidChangeNotification 事件:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNowPlayingItemChangedEvent:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:self.myMusicPlayer];
    

    这会注册一个事件处理程序,只要当前播放的歌曲发生变化,就会调用该事件处理程序。

    然后在你的 MPMusicPlayerController 上调用beginGeneratingPlaybackNotifications 方法,告诉它开始向你发送播放通知。

    [self.myMusicPlayer beginGeneratingPlaybackNotifications];
    

    您可以根据需要通过调用beginGeneratingPlaybackNotificationsendGeneratingPlaybackNotifications 来控制何时收到通知。

    然后创建事件处理程序。这是每次 MPMusicPlayerControllerNowPlayingItemDidChangeNotification 触发时都会调用的方法:

    - (void)handleNowPlayingItemChangedEvent:(NSNotitication*)notification
    {
        // Update the lock screen info here
    }
    

    现在,只要当前播放的歌曲发生变化,您的事件处理程序就会被调用,您可以更新您正在播放的信息。

    【讨论】:

    • Loughiln 如果我不使用 MPMusicPlayerController 播放音乐会怎样?
    猜你喜欢
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    相关资源
    最近更新 更多