2017-05-05 71 views
0

我有音樂播放器應用程序,當應用程序轉到背景時,它會在鎖定的屏幕上顯示音樂控制,在我的情況下,正在播放廣播藝術家和歌曲。我使用下列內容:刷新應用程序狀態在背景上運行

- (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我猜應用程序最初進入後臺時只會調用一次。

回答

1

MPMusicPlayerController類有一些方法和事件來幫助解決這個問題。

首先,你需要告訴你的應用程序來監聽MPMusicPlayerControllerNowPlayingItemDidChangeNotification事件:

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

這將註冊的事件處理函數被調用時正在播放的歌曲的變化。

然後調用您的MPMusicPlayerController上的beginGeneratingPlaybackNotifications方法,告訴它開始向您發送播放通知。

[self.myMusicPlayer beginGeneratingPlaybackNotifications]; 

當你想要得到通知,並可以控制,當你根據需要調用beginGeneratingPlaybackNotificationsendGeneratingPlaybackNotifications沒有。

然後創建事件處理程序。這是將被調用每次MPMusicPlayerControllerNowPlayingItemDidChangeNotification火災的方法:

現在,只要當前播放歌曲的變化,你的事件處理程序將被調用,您可以更新你現在玩的信息。

+0

Loughiln如果我沒有使用MPMusicPlayerController播放音樂,該怎麼辦? –

相關問題