I can currently get whatever song is playing, and get a UILabel of one song's information, but when the song changes, the new song's information is not added to a new cell in a uitable. How do I get the new songs info to be added to new cells, every time a new song is played?
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
musicPlayer.beginGeneratingPlaybackNotifications()
playButton = UIButton()
let image = "playbutton.png"
playButton.setImage(UIImage(named:image), forState: .Normal)
playButton.addTarget(self, action: "play:", forControlEvents: UIControlEvents.TouchUpInside)
// Do any additional setup after loading the view.
}
func getNowPlayingItem() {
if let nowPlaying = musicPlayer.nowPlayingItem {
let title = nowPlaying[MPMediaItemPropertyTitle] as? String
let artist = nowPlaying[MPMediaItemPropertyArtist] as? String
let album = nowPlaying[MPMediaItemPropertyAlbumTitle] as? String
println("Song: \(title)")
println("Artist: \(artist)")
println("Album: \(album)")
println("\n")
self.add = [Play(name: "\(title!)\n\(artist!)\n\(album!)")]
self.table.rowHeight = UITableViewAutomaticDimension
self.table.estimatedRowHeight = 44.0
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.add.count
//return count of objects in array
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = self.table.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
var play: Play
play = add[indexPath.row]
cell.textLabel?.text = play.name
cell.textLabel?.numberOfLines = 3;
cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
playButton.tag = indexPath.row
return cell
}
答案 0 :(得分:1)
You can register for MPMusicPlayerControllerNowPlayingItemDidChangeNotification notification as detailed in https://developer.apple.com/library/ios/documentation/Audio/Conceptual/iPodLibraryAccess_Guide/UsingMediaPlayback/UsingMediaPlayback.html#//apple_ref/doc/uid/TP40008765-CH100-SW1
And then in the notification selector, call getNowPlayingItem to add the new song to your table.
You also have to create a new Play object with the new song info and add it to your self.add array.
let name = title + "\n" + artist + "\n" + album + "\n";
self.add.append(Play(name: name));