使用 -[MPMediaPlaylist addItemWithProductID:completionHandler:] 时出错

Error when using -[MPMediaPlaylist addItemWithProductID:completionHandler:]

我正在尝试使用 Apple Music 9.3 中的新 API 将歌曲添加到我的应用程序创建的播放列表中,而不是将其添加到用户的音乐库中。

考虑产品 ID 316654632,这是美国 iTunes Store 中 Phoenix 的歌曲 Lisztomania。

使用下面的代码,我可以播放歌曲

MPMusicPlayerController *musicPlayer = [MPMusicPlayerController systemMusicPlayer];  
[musicPlayer setQueueWithStoreIDs:@[@"316654632"]];  
[musicPlayer play];  

使用以下代码,我可以将歌曲添加到我的 Apple Music 资料库

[[MPMediaLibrary defaultMediaLibrary] addItemWithProductID:@"316654632" completionHandler:^(NSArray<__kindof MPMediaEntity *> * _Nonnull entities, NSError * _Nullable error) {  
    NSLog(@"%@", error);  
}];  

错误为零,我可以在我的库中看到这首歌。

但是对播放列表进行同样的尝试是行不通的。

[[MPMediaLibrary defaultMediaLibrary] getPlaylistWithUUID:uuid creationMetadata:[[MPMediaPlaylistCreationMetadata alloc] initWithName:@"Test Playlist"] completionHandler:^(MPMediaPlaylist * _Nullable playlist, NSError * _Nullable error) {  
    NSLog(@"%@", error);

    if (!error) {  
        [playlist addItemWithProductID:@"316654632" completionHandler:^(NSError * _Nullable error) {  
            NSLog(@"%@", error);  
        }];  
    }  
}];  

播放列表已创建,我可以在 Music.app 中看到它,但是当我尝试将我播放并添加到我的库中的相同产品 ID 添加到播放列表时,出现错误

Error Domain=MPErrorDomain Code=4 "The requested id could not be found" UserInfo={NSLocalizedDescription=The requested id could not be found}

但是,如果我成功将相同的项目添加到我的库中,怎么会找不到呢?

更新

好消息! Apple 在 10.2.1!

上修复了 rdar://26408683

在我的播放列表转换应用程序 (mixlib) 中,我发现将一些曲目可靠地添加到新创建的播放列表的唯一解决方案是 等待

在我的测试中,等待五秒钟似乎就足够了。

[[MPMediaLibrary defaultMediaLibrary] getPlaylistWithUUID:uuid creationMetadata:[[MPMediaPlaylistCreationMetadata alloc] initWithName:@"Test Playlist"] completionHandler:^(MPMediaPlaylist * _Nullable playlist, NSError * _Nullable error) {  
if (!error) {  
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 /*seconds*/ * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)), ^() {
        [playlist addItemWithProductID:@"316654632" completionHandler:^(NSError * _Nullable error) {  
            NSLog(@"%@", error);  
    }];  
}  
}];  

我怀疑这是一个 server/network 相关的问题,因为它有时无需等待即可运行。找不到的"requested id"可能是播放列表id,不是曲目id。

当它开始对播放列表起作用时,它就会一直起作用。因此,您无需在添加每个额外曲目之前等待,而只需在添加第一个曲目之前等待。