Question

When i retrieve Media Info like Artist , Album , Song Title from MPMediaItem in iOS, However some songs doesn't have Artist Name and Album.

So i got return value with NULL

Here is my codes

MPMediaItem *currentItem = self.player.nowPlayingItem;

    NSString *Artist = [currentItem valueForProperty:MPMediaItemPropertyArtist];
    NSString *Title = [currentItem valueForProperty:MPMediaItemPropertyTitle];
    NSString *Album = [currentItem valueForProperty:MPMediaItemPropertyAlbumTitle];

If song doesn't have Artist and Album name , it's return NULL Value.

I want to replace that NULL value with Unknown value.

How can i replace it?

Thanks for your reading.

Was it helpful?

Solution

If you want to be elegant, you can add a category to MPMediaItem like this:

@implementation MPMediaItem (Readable)

- (id)readableValueForProperty:(NSString *)prop
{
    id originalValue = [self valueForProperty:prop];

    if (originalValue == nil) {
        return @"Unknown";
    }

    return originalValue;
}

@end

Then you can call it like this:

NSString *artist = [currentItem readableValueForProperty:MPMediaItemPropertyArtist];

Note that this is dangerous if you're getting a property that isn't an NSString originally. If you're operating with string values only, this should be fine, though.

An approach which is always safe but less readable (and more redundant) would be checking each and every returned value by hand:

NSString *artist = [currentItem valueForProperty:MPMediaItemPropertyArtist];
if (artist == nil) artist = @"Unknown";

OTHER TIPS

- (NSString*)getValueFromMediaItem:(MPMediaItem*)item forKey:(NSUInteger)key
{
    NSString * value = [item valueForProperty:key];

   if([value isKindOfClass:[NSNull class]] || !value)
      return @"Unknown";

    return value;
}

//call this by:
    NSString *Artist = [self getValueFromMediaItem:currentItem forKey: MPMediaItemPropertyArtist];
  if (strArtist==nil)
        {
            NSString *emptystring=@" ";
            [ArrayArtist addObject:emptystring];
        }
        else
        {
            [ArrayArtist addObject:strArtist];

        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top