-2

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

enter image description here

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Sophman
  • 85
  • 2
  • 17

1 Answers1

1

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].)

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And see my book and its example code for lots of examples and discussion: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch16p678mediaQuery/ch29p946mediaQuery/ViewController.swift – matt Dec 22 '15 at 16:22
  • thank you!! I got it now. That makes perfect sense.. I appreciate your help matt!! – Sophman Dec 22 '15 at 16:25