0

Why does the following result in a tableview full of "Artist" instead of a tableview full of actual artist names? Where did I go wrong? How do I pull the artist value from a collection? All help is appreciated...

var tableData = MPMediaQuery.artistsQuery()

override func viewDidLoad() {
    super.viewDidLoad()
    self.artistTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
    tableData.groupingType = MPMediaGrouping.Artist
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.tableData.collections!.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell     {
    let cell: UITableViewCell = self.artistTableView.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
    let artist: MPMediaItemCollection = tableData.collections![indexPath.row]

    if artist.valueForProperty(MPMediaItemPropertyArtist) == nil {
        cell.textLabel?.text = "Artist" as String
    } else {
    let artistName = artist.valueForProperty(MPMediaItemPropertyArtist) as! NSString
    cell.textLabel?.text = artistName as String
    }
    return cell
}
rocketman240
  • 119
  • 12

1 Answers1

1

You access the properties of a MPMediaItemCollection via it's representativeItem. You fetch the artist's name like so:

let artist : MPMediaItemCollection = tableData.collections![indexPath.row]
let artistName = artist.representativeItem.artist ?? "Unknown Artist"

Though if I were you I wouldn't forcibly unwrap tableData.collections because if your user has an empty iTunes library that line will case the application to crash.

Wes
  • 1,032
  • 7
  • 11
  • xcode forces me to do something like (tableData.collections?)! is this any better? – rocketman240 Apr 03 '16 at 21:49
  • @rocketman240 you want to use optional binding or check with `guard` to make sure `tableData.collections` isn't nil. For example `if let collections = tableData.collections { // proceed as you did before }` or `guard let collections = tableData.collections else { // handle else } ` – Wes Apr 04 '16 at 01:05