Playing a video in swift is not a very complex task, but thanks to frameworks provide by apple. AVKit framework provides a high level player interface for developer’s to play video in swift language. AVPlayerViewController’s player is capable of playing video, either from file stored locally inside the app bundle or from a file hosted on remote URL.
Steps to play video using AVPlayerViewController
AVPlayerViewController gives developer ability to use system default player as system player is supplied with in built playback controls. Since AVPlayer of AVPlayerViewController has playback controls. So developer’s need not to worry of doing extra coding for handling video playback.
In this tutorial we, will learn how to play video in swift using AVPlayerViewController.
1: Import AVKit framework
import UIKit import AVKit
2: Get file path of the video you want to play in AVPlayer. We will use guard statement because if file is not found then we will not play video.
guard let filePath = Bundle.main.path(forResource: "A", ofType: "mp4") else { return}
3: Create an instance of AVPlayer using the above file path.
let player = AVPlayer(url: URL(fileURLWithPath: filePath))
4: Next, create an instance of AVPlayerViewController
let vc = AVPlayerViewController()
5: Assign player created in step 3, to AVPlayerViewController’s property named player.
vc.player = player
6: Finally, present AVPlayerViewController on to the screen.
present(vc, animated: true)
Output:
Where to go from here
In this tutorial, we learned how to play video in swift using AVPlayerViewController of AVKit framework in ios sdk. Video can be played using a local video file and also from a url for the video file hosted on remote server.