Reputation: 6940
I have music player app, and when app goes background it show music control on locked screen, in my case currently playing on radio artist and song. I use following:
- (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)
};
}
Problem is, when data changed and next song will be on radio, how do i tell my app to refresh itself? applicationWillResignActive
i guess called only once when app initially goes to background.
Upvotes: 0
Views: 169
Reputation: 4174
The MPMusicPlayerController
class has some methods and events to help with this.
First you need to tell your application to listen for the MPMusicPlayerControllerNowPlayingItemDidChangeNotification event:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNowPlayingItemChangedEvent:) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:self.myMusicPlayer];
This registers an event handler that gets called whenever the currently playing song changes.
Then call the beginGeneratingPlaybackNotifications
method on your MPMusicPlayerController to tell it to start sending you playback notifications.
[self.myMusicPlayer beginGeneratingPlaybackNotifications];
You can control when you want to be notified and when you don't by calling beginGeneratingPlaybackNotifications
and endGeneratingPlaybackNotifications
as needed.
Then create the event handler. This is the method that will get called every time the MPMusicPlayerControllerNowPlayingItemDidChangeNotification fires:
- (void)handleNowPlayingItemChangedEvent:(NSNotitication*)notification
{
// Update the lock screen info here
}
Now whenever the currently playing song changes, your event handler will get called and you can update your now playing info.
Upvotes: 1