AVPlayerViewController
AVKit
Swift
video playback
iOS development

How to play video with AVPlayerViewController AVKit in Swift

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

AVKit provides a sophisticated and high-level interface for integrating video playback into your iOS applications. At the core of this offering is AVPlayerViewController, a robust tool that displays video content using AVPlayer. This article provides a comprehensive guide to using AVPlayerViewController in Swift, including practical examples and technical insights to help you efficiently integrate video playback into your applications.

Getting Started with AVPlayerViewController

AVPlayerViewController is part of the AVKit framework and simplifies the process of implementing a media player interface. It manages most of the user interface (UI) concerns and is equipped with features like play/pause, skip forward/backward, and volume control.

Importing the Necessary Frameworks

To start using AVPlayerViewController, you need to import AVKit and AVFoundation, as AVPlayer is a part of AVFoundation.

swift
import AVKit
import AVFoundation

Setting Up the AVPlayer

Before presenting AVPlayerViewController, you must create an instance of AVPlayer. This instance is responsible for handling playback.

swift
1// Example URL of the video to be played
2guard let url = URL(string: "https://www.example.com/video.mp4") else {
3    fatalError("Invalid URL")
4}
5
6// Create an AVPlayer instance
7let player = AVPlayer(url: url)

Initializing the AVPlayerViewController

Once you have your AVPlayer set up, you can create an instance of AVPlayerViewController and assign the player to it.

swift
1// Initialize AVPlayerViewController
2let playerViewController = AVPlayerViewController()
3
4// Assign the player to the view controller
5playerViewController.player = player

Presenting AVPlayerViewController

After initializing and configuring your AVPlayerViewController, you can present it.

swift
1// Present the player view controller
2self.present(playerViewController, animated: true) {
3    // Start playing the video when the view appears
4    player.play()
5}

This setup will display the video in a full-screen player with built-in controls.

Customizing the Video Player

Though AVPlayerViewController comes with default controls, you can customize the experience further. Here are some customization options:

Adding Observers

You can observe the player's properties such as the playback status.

swift
// Add observer for player's status
player.addObserver(self, forKeyPath: "status", options: [.new], context: nil)

Implement the following method to handle the observed changes:

swift
1override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
2    if keyPath == "status" {
3        if player.status == .readyToPlay {
4            // The player is ready
5        }
6    }
7}

Managing Playback Controls

You can manage playback states like play, pause, and stop programmatically:

swift
player.play()   // Start or resume playback
player.pause()  // Pause the playback
player.seek(to: CMTime(seconds: 0, preferredTimescale: 1)) // Seek to the beginning

Handling Playback Notifications

Register for notifications to handle events like completion of playback:

swift
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)

Implement the selector method:

swift
@objc func playerDidFinishPlaying() {
    print("Video finished playing.")
}

Common Pitfalls

  • Presenting AVPlayerViewController before the AVPlayer is configured and ready to use.
  • Updating playback-related UI from background callbacks instead of the main thread.
  • Forgetting to remove observers or notifications when custom playback monitoring is added.
  • Assuming default controls are enough when the app also needs accessibility, error handling, and network-awareness.
  • Treating remote playback as trivial and then debugging buffering and state issues too late.

Summary

  • 'AVPlayerViewController is the standard high-level UIKit tool for video playback in Swift.'
  • Pair it with AVPlayer, present it normally, and start playback when presentation completes.
  • Add observers and notifications only when you need extra playback state handling.
  • Keep threading, cleanup, and remote-stream error handling explicit in production code.
  • Use the built-in controller when possible and customize only where the product really needs it.

Course illustration
Course illustration

All Rights Reserved.