MPMediaLibraryDidChangeNotification called twice?

2019-05-10 17:23发布

My app uses the iPodMusicPlayer and, when suspended, the user might go out and make changes in Apple's Music App, for example creating or modifying a Playlist, then return to my App.

I receive the expected MPMediaLibraryDidChangeNotification, which is fine and I deal with it updating my references etc., but I receive a second MPMediaLibraryDidChangeNotification about 2 minutes later which I really don't need.

Any ideas on avoiding this second notification?

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification_iPodLibraryDidChange:) name: MPMediaLibraryDidChangeNotification object:nil];

[[MPMediaLibrary defaultMediaLibrary] beginGeneratingLibraryChangeNotifications];

5条回答
聊天终结者
2楼-- · 2019-05-10 17:57

The notification can be called multiple times depending on what's going on. For example, if you add an album to your phone with 12 songs in it, the notification gets called 12 times. Basically it gets called every time the library changes and not just when the sync has finished (at least on iOS 5.1, not sure about older iOS versions).

查看更多
一夜七次
3楼-- · 2019-05-10 18:00
if( !self.lastModifiedDate )        self.lastModifiedDate = [[NSDate alloc] init];
if( [self.lastModifiedDate compare:[[MPMediaLibrary defaultMediaLibrary] lastModifiedDate]] == NSOrderedSame )  return;
self.lastModifiedDate = [[MPMediaLibrary defaultMediaLibrary] lastModifiedDate];

The above lines in my notification handler method deal with the extra call. Still no idea why I'm getting it.

查看更多
做个烂人
4楼-- · 2019-05-10 18:10

Where are you adding he observer? For example, if you add in the viewWillAppear and only remove observers in dealloc, you may have multiple observers which is causing a problem. At least, when I encountered a problem like this it was because I had inadvertently added a second observer without removing all the previous.

2 minutes seems like a long lag time (mine was a few seconds), but still may be worth checking out.

查看更多
Luminary・发光体
5楼-- · 2019-05-10 18:15

Remove the beginGeneratingLibraryChangeNotifications command, and it will fix it. :) You just get every notification for changed, one from the notification center, and one from the default library.

查看更多
虎瘦雄心在
6楼-- · 2019-05-10 18:19

Probably the best way to avoid multiple launches of update procedures after multiple notifications is to set a timer and wait some seconds before performing the actual update.

查看更多
登录 后发表回答