Skip to content

SwiftUI: VideoPlayer

In the recent WWDC 2020, Apple introduced VideoPlayer where you will be able to play videos either through a local videos or URL.

However, you won’t be able to use videos from YouTube.

A view that displays the video content from a player object along with system-supplied playback controls.

Apple Documentation

Prerequisites

To follow along this tutorial, you’ll need some basic knowledge in:

  • A basic familiarity with Swift.
  • At least Xcode 12+
  • Only supports iOS 14+

Getting Started With VideoPlayer

To begin, you will first need to import the required module.

For the purpose of illustration, I will download Nyan Cat video from YouTube which will have a mp4 extension. If you are curious what the video is, you can check out the video.

The file will then be placed inside the project as shown under here. Please make sure that the target is selected or else your app will crash.

Please test it only on your device. Testing it on the simulator will not work.

By using the code below, you have now create a VideoPlayer in SwiftUI.

And you can check out the cool result where fast forward & rewind 15 seconds, dragging the progress indicator and going full screen.

Other than using local files, you can definitely opt for a URL. Do note that YouTube link will not work here.

You can use m3u8 file with one example seen on the web and the implementation is as followed. Do make sure that the file does exist when using force unwrap. It’s not a good practice to force unwrap most of the time.

One cool thing that you can definitely do on your video is adding an overlay! This is mostly used to portray your logo.

Here you will portray your own logo and it will appear on the bottom right.

With a little tweak, you can move your logo to the top left by using topLeading.

Where to go From Here

If you feel like you are ready to take on more challenges, feel free to check out some other tutorials that we have created:

Published inSwiftUI

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *