I'm looping through all the songs from an iPhone's music library using the following code:
NSArray * songs = [[NSArray alloc] initWithArray:[[MPMediaQuery songsQuery] collections]];
for (MPMediaItemCollection * item in songs){
NSString * persistentID = [[[item representativeItem] valueForProperty:MPMediaItemPropertyPersistentID] stringValue];
// Do something with it.
}
[songs release];
Pretty basic stuff.
I'm getting the PersistentID as an NSString
because I need to write it to an XML file (for transmission over a network to another device). Hence the reason I can't just leave it as an NSNumber
.
The other device will then ask for the iPhone to play a track by transmitting the PersistentID back again.
At this point, the iPhone has an NSString
of the PersistentID of the track it should play.
It would be combersome to loop through every song again and compare PersistentIDs until I find the track I want, so I'm trying to use the MPMediaPropertyPredicate
to have the iPhone search for me.
I'm using the following code for the search:
MPMediaPropertyPredicate * predicate = [MPMediaPropertyPredicate predicateWithValue:persistentID forProperty:MPMediaItemPropertyPersistentID];
MPMediaQuery * songsQuery = [[MPMediaQuery alloc] init];
[songsQuery addFilterPredicate:predicate];
if ([[songsQuery items] count]){
MPMediaItem * item = [[songsQuery items] objectAtIndex:0];
// Play item.
}
[songsQuery release];
Where persistentID
is the NSString
from earlier.
Weirdly, this works for some songs, not for others. i.e, sometimes the items
array is not empty, even though I'm passing an NSString
, not an NSNumber
.
I'm wondering if there's a way to convert my NSString
back to the NSNumber
it came from, and how I can do that.
UPDATE: I've tried the NSNumberFormatter, I've also tried something like:
[NSNumber numberWithFloat:[persID floatValue]];
I've tried all the standard ways of doing it without prevail.
This is working pretty well, no problems so far:
unsigned long long ullvalue = strtoull([persistentID UTF8String], NULL, 0);
NSNumber * numberID = [[NSNumber alloc] initWithUnsignedLongLong:ullvalue];
MPMediaPropertyPredicate * predicate = [MPMediaPropertyPredicate predicateWithValue:numberID forProperty:MPMediaItemPropertyPersistentID];
[numberID release];
// And so on.
Hope this helps anyone else who ran into this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With