How to pull the artist value from MPMediaItemCollection

喜欢而已 提交于 2019-12-08 12:38:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!