Coded using Swift 3

Add a table view controller to the main storyboard. Stretch out the prototype cell and add a UILabel and a UIView. Also create a new Cocoa Touch Class file that derives from UITableViewController named VideoTableViewController.swift. Make sure to map it with the view controller in the storyboard:

Create a new Cocoa Touch Class file deriving from UIView named PlayerView.swift. Add the following code below:

This is a convenient way of using the AVPlayerLayer, as described by here. Now map this to the UIView object that was added to the prototype cells to act as a placeholder for our video playback layer.

Create a new Cocoa Touch Class file deriving from UITableViewCell named VideoTableViewCell.swift. Set the table view cell’s custom class to the file you just created and create two IBOutlets; one for the UILabel and one for the UIView – which should now be the PlayerView:

In VideoTableViewController.swift, we’ll need to import the AVKit and AVFoundation frameworks here as well. We’ll be utilizing the AVPlayer and AVPlayerLayer classes to utilize the PlayerView class we created earlier which will allow us to manager playback of videos. We’re going to be using table view delegate methods to do this; cellForRowAt, willDisplay, and didEndDisplaying:

The breakdown:

cellForRowAt:

This is where the cell is created. Since the VideoTableViewCell has a PlayerView property, we can easily set its player value by creating it within the function. The AVPlayer is what manages the playback of the video, but it does not display it on the screen to be able to see. For that to happen, it needs the AVPlayerLayer to do that for it. That is why both are needed to display videos. We could tell the player to use its play() function here, but that would make all the cells play when they are created.

willDisplay:

This is where we will execute the play() function. Whenever a cell is going to be displayed, it will execute this method. I added just a very minor functionality here to avoid things playing, but it will need to be altered. I say that the smallest index of visible cells can play.

didEndDisplaying:

This is where we pause the player and set it to nil so we’re not holding onto resources.

Also make sure to set allow arbitrary loads in your info.plist file as well:

Definitely got help with this from these sources:

http://stackoverflow.com/questions/40870916/how-to-handle-avplayer-in-a-uitableviewcell
http://stackoverflow.com/questions/33702490/embedding-videos-in-a-tableview-cell
http://stackoverflow.com/questions/38329789/avplayer-not-working-ios-swift

This is quick overview and you will need to fix it to work efficiently.

Hopefully this helps though!

1 thought on “Quick Swift – Play Video in UITableViewCell

Comments are closed.

Back To Top