Software Development Preston / Code  / Swift 3 – Embed a video in UITableViewCell

Swift 3 – Embed a video in UITableViewCell

Swift 3 – Embed a video in UITableViewCell

For a recent project we were working on, we had to embed a video player to play MP4 videos from URLs into a UITableViewCell. This sounds relatively easy but we had a few issues along the way so I thought it worth a blog post to help others facing the same challenges.

The idea is simple – embed an AVplayer into a UITableViewCell and update the URL each time the cell is reused. So, let’s do that:

So now we have a basic cell setup with an embedded video player. We can create and display the cell in our UITableViewController:

Great! But where’s the video? Well, we need to set that somehow in the cellForRowAt call so we’re going to need a method to set the URL in the VideoCell:

So now we have a videoItemUrl property which we can use to set the URL in the table view controller:

We use the didSet property observer to let us run some additional code at the point where the new URL has been set, in this case we have a function called initNewPlayerItem inside the VideoCell:

At this point you can build and run the code and your videos will be displayed.

But wait!

The table view is not responsive and freezes while you scroll. Why is this? Well, after running the app through Instruments and watching what was going on we could see that the call to replaceCurrentItem blocks the main thread while it gathers information about the video. That’s unacceptable as it makes the app look slow and unresponsive, certain to be immediately deleted!

So, what do we do now? Well, the reason it’s blocking is that it is loading information about the video from the URL which takes some time so we need to move this off to a background thread:

This tells the AVAsset to load the values for “duration” in the background, this is enough information to display the video and not block the main thread so that’s good enough for us. There is a chance that the load will fail or be cancelled so we need to make sure we actually have the value or else we’re back to buggy scrolling!

Finally, at the top of the initNewPlayerItem function we need to cancel the load, this is for the case when the cell is reused before the video metadata has been successfully loaded:

Now, when you run the app you will see smooth scrolling and videos loading in the background without freezing the app!

I hope this helps somebody out there! More to come….

Facebook Comments