问题
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
}
回答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.
来源:https://stackoverflow.com/questions/36391214/how-to-pull-the-artist-value-from-mpmediaitemcollection