I wrote the following function that reads through the list of media items in my iTunes directory and returns the music files. I need to return the "song titles" but when I run it the items returned are in an unknown format. I am pretty sure I need to run them through a property filter or use some conversion to get the actual names correctly. At the end I want to output the contents in an array of Strings. I only run the loop four times in the screen shot attached. Can anyone point me to a missing conversion? It looks like the output is in hex format but not clear on that.
class func readMusicFiles() -> NSMutableArray {
//var songDecoded:[NSMutableArray]
let result = NSMutableArray()
let allSongsQuery:MPMediaQuery = MPMediaQuery.songsQuery();
let tempArray:NSArray = allSongsQuery.items!;
for item:AnyObject in tempArray {
if (item is MPMediaItem) {
let temp = item as! MPMediaItem;
if (temp.mediaType != MPMediaType.Music) {
continue;
}
result.addObject(item);
}
}
print(result)
return result
}
}
The output looks like this
The "hex" is not a "format"; it's merely an indication of the memory address of the object. Ignore it.
You've got your media items (songs in this case). Now, instead of saying print(result)
, ask for their titles:
for song in result {
print(song.title)
}
Or, to make a new array:
let titles = result.map {$0.title}
(Also, do not declare your function to return an NSMutableArray. That's a Cocoa thing. Try to stick to Swift arrays. For example, if you are going to end up with an array of titles, those are strings, so return a [String]
.)