简体   繁体   中英

How can I pause AVPlayer in UITableViewCell (Swift)?

I am broadcasting stations in a table and am trying to figure out how to pause the station when the cell is clicked. I can get it to play but not pause. Also is there anyway to indicate that the current cell is playing. I am wondering because I am not able to access my custom cell outside of the cellforindexpath function. Here is my code.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let myCell:BroadcastTableViewCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as! BroadcastTableViewCell

    // Configure the cell...
    myCell.broadcaster.text = broadcasters[indexPath.row]
    myCell.isBroadcasting.text = timePlayed[indexPath.row]
    return myCell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
   // self.performSegueWithIdentifier("toBroadcastView", sender: self)

    self.player = AVPlayer(URL: NSURL(string: stations[indexPath.row]))

    if selectedPath == indexPath.row{
        if status == 0{
            player.play()
            status += 1
        }else{
            player.pause()
            status -= 1
        }
    }else{
        status = 0
        player.play()
    }

    selectedPath = indexPath.row

}

AVPlayer has a rate property that = 0.0 when it is not playing and <= 1.0 when it is playing.

If you only want one broadcasting station to play at once, you can instantiate an AVPlayer in a singleton class, and change the AVPlayerItem based on what station is playing. In this way, you will only ever have one instance of an AVPlayer, and instead of checking if that custom cell is playing, you can check if the AVPlayer itself is playing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM