iosswiftavplayeravplayerlayer

AVPlayer in UITableViewCell results in "Unexpectedly found nil while implicitly unwrapping an Optional value" error


I am trying to setup a custom UITableViewCell that will include a video player in the cell.

I am getting a "Unexpectedly found nil while implicitly unwrapping an Optional value" on the line:

"playerLayer.frame = self.videoPlayerSuperView.bounds"

Here is the code I am using:

import UIKit
import AVFoundation

class feedCell: UITableViewCell {


    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var viewsLabel: UILabel!
    @IBOutlet weak var postTextLabel: UILabel!
    @IBOutlet weak var videoPlayerSuperView: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        let videoURL = URL(string: "https://some.url.of.an.mp4")
        let player = AVPlayer(url: videoURL!)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.videoPlayerSuperView.bounds
        self.videoPlayerSuperView.layer.addSublayer(playerLayer)
        player.play()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
}

How do I resolve this?


Solution

  • Thanks to @AjinkyaSharma

    override func layoutSubviews() {
            super.layoutSubviews()
    
            let videoURL = URL(string: "https://some.url.of.an.mp4")
            let player = AVPlayer(url: videoURL!)
            let playerLayer = AVPlayerLayer(player: player)
            playerLayer.frame = self.videoPlayerSuperView.bounds
            self.videoPlayerSuperView.layer.addSublayer(playerLayer)
            player.play()
    }