URL to MPMediaItem

帅比萌擦擦* 提交于 2019-12-20 10:53:46

问题


I have a simple question but i can't found a right answer. I have a song url saved to my database. An path Like this.

aSound.path = [[item valueForProperty: MPMediaItemPropertyAssetURL] absoluteString];

How to convert back to a MPMediaItem object wich has songname artist and artwork?

Is it possible?

Thanks the answers.


回答1:


Saving:

    NSNumber* persistentID = 
[mediaItem valueForProperty:MPMediaItemPropertyPersistentID];

Loading:

            MPMediaPropertyPredicate * predicate = 
              [MPMediaPropertyPredicate 
                predicateWithValue:persistentID 
                       forProperty:MPMediaItemPropertyPersistentID];

Another example: NSNumber for MPMediaItemPropertyPersistentID to NSString and back again

Note song URLs are are unreliable because any DRM song returns a null url




回答2:


Alternatively, a nasty hack that Works For Me (tm).

- (MPMediaItem *)getMediaItemForURL:(NSURL *)url {
    // We're going to assume that the last query value in the URL is the media item's persistent ID and query off that.

    NSString *queryString = [url query];
    if (queryString == nil) // shouldn't happen
        return nil;

    NSArray *components = [queryString componentsSeparatedByString:@"="];
    if ([components count] < 2) // also shouldn't happen
        return nil;

    id trackId = [components objectAtIndex:1];

    MPMediaQuery *query = [[MPMediaQuery alloc] init];
    [query addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:trackId forProperty:MPMediaItemPropertyPersistentID]];

    NSArray *items = [query items];

    if ([items count] < 1) // still shouldn't happen
        return nil;

    return [items objectAtIndex:0];
}

Comments appreciated for where this might go wrong or how to improve it. I prefer to pass the URL around instead of the PersistentID as I have multiple media sources, all of which can use URLs. Using the PersistentID would mean a lot of "if this is a media ID, do this, otherwise, do that with the URL".



来源:https://stackoverflow.com/questions/9890500/url-to-mpmediaitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!