Complete Guide to Playing Local Video Files in Swift: Using AVPlayer and AVPlayerViewController

Dec 02, 2025 · Programming · 28 views · 7.8

Keywords: Swift | iOS | AVPlayer | Video Playback | Local Files

Abstract: This article details the technical implementation of playing local video files in iOS applications using Swift. Through the AVPlayer and AVPlayerViewController frameworks, developers can easily integrate video playback functionality. Starting from project configuration, it step-by-step explains video file addition, Bundle resource management, code implementation, error handling, and provides optimization tips and common issue solutions. Based on high-scoring Stack Overflow answers and best practices, it is suitable for iOS developers.

In iOS app development, integrating video playback is a common requirement, especially for handling locally stored video files. Swift, as a modern programming language, offers robust video processing capabilities through the AVFoundation and AVKit frameworks. This article delves into how to play local videos in Swift, implementing a complete and efficient solution based on AVPlayer and AVPlayerViewController.

Project Configuration and Resource Management

First, ensure the video file is correctly added to the Xcode project. Recommended formats include .m4v or .mp4, as they have good compatibility on iOS. In Xcode, navigate via Project Navigator (shortcut cmd + 1) to the project root, select the target, go to the Build Phases tab, and check the Copy Bundle Resources section. The video file must be in this list; otherwise, it will be inaccessible at runtime. If missing, use the plus button to add it. This step is crucial because the Bundle is the core storage for app resources, and video files need to be included for proper loading by code.

Core Code Implementation

In the ViewController, import the necessary frameworks: AVKit for interface control and AVFoundation for low-level media handling. The following code example demonstrates the core logic for playing a video:

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playVideo()
    }

    private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType: "m4v") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        let playerController = AVPlayerViewController()
        playerController.player = player
        present(playerController, animated: true) {
            player.play()
        }
    }
}

The code first calls the playVideo function in the viewDidAppear method to ensure playback starts after the view loads. In playVideo, use Bundle.main.path(forResource:ofType:) to get the video file path, which returns an optional value handled with a guard statement to avoid crashes if nil. If the file is not found, output debug information and return. Then, create an AVPlayer instance with the file URL, initialize an AVPlayerViewController, and set its player property. Finally, present the player controller modally via the present method and call play() in the completion closure to start playback.

Error Handling and Optimization

In real-world applications, enhance error handling. For example, add user-friendly alerts instead of just debug output. Consider using UIAlertController to notify users if the file is missing. Additionally, video playback may involve performance issues like memory management. It is advisable to pause or stop playback when the view disappears to release resources:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    playerController.player?.pause()
}

For large video files, asynchronous loading and buffering are optimization points. AVPlayer handles buffering automatically, but developers can monitor states (e.g., AVPlayerItem.status) to provide loading indicators. Also, supporting multiple video formats (e.g., .mov, .avi) requires checking device compatibility; iOS typically supports H.264-encoded MP4 files.

Supplementary References and Advanced Topics

Other answers mention using MPMoviePlayerController (now deprecated) or custom playback interfaces, but AVPlayerViewController is Apple's recommended standard, offering built-in controls (play, pause, progress bar, etc.). For advanced needs, such as custom UI or streaming, integrate AVPlayerLayer directly into a view. For example:

let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = view.bounds
view.layer.addSublayer(playerLayer)
player.play()

This allows more flexible layouts but requires manual control addition. In summary, Swift combined with AV frameworks provides powerful support for video playback, and following this guide enables quick implementation and optimized user experience.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.