Play video in swift using AVPlayerViewController

Playing a video in swift is not a very complex task, thanks to frameworks provide by apple. AVKit framework provides a high level interface for developer to play video in swift language. AVPlayerViewController’s player is capable of playing video, either from stored locally or from a remote URL.

Steps to play video in swift using AVPlayerViewController

AVPlayerViewController gives developer ability to use system default player with system supplied playback controls. In this tutorial we, will learn how to play video using AVPlayerViewController.

1: Import AVKit framework

import UIKit
import AVKit

2: Get file path of the video you want to play in AVPlayer.

guard let filePath = Bundle.main.path(forResource: "A", ofType: "mp4") else { return}

3: Create an instance of AVPlayer

  let player = AVPlayer(url: URL(fileURLWithPath: filePath))

4: Create an instance of AVPlayerViewController

 let vc = AVPlayerViewController()

5: Assign player created in step 3, to AVPlauerViewController’s property named player.

vc.player = player

6: Present AVPlayerViewController on to the screen.

present(vc, animated: true)

Output:

Video getting played inside AVPlayerViewController-play video in swift

Where to go from here

In this tutorial, we learned how to play video in swift, using AVPlayerViewController of AVKit framework in ios sdk.

More tutorial on swift

Property Observers in swift

Create custom UIView class with xib in swift

%d bloggers like this: