How to play a local video with Swift?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Playing a local video in iOS is straightforward with AVPlayer and AVPlayerViewController. The key is locating the file URL correctly, configuring the player on the main thread, and handling playback lifecycle events. This approach works for bundled files and app sandbox files.
Play a Bundled Video with AVPlayerViewController
If the video is included in the app bundle, resolve it with Bundle.main.url and pass it to AVPlayer.
Add demo.mp4 to target membership in Xcode so the file is copied into the app bundle.
Play a File from Documents Directory
For downloaded or generated videos, build a URL in the app documents folder.
Then use the same AVPlayer initialization pattern as bundled assets.
Embed Player in View Hierarchy
If you want inline playback instead of a modal controller, attach AVPlayerLayer to a custom view.
Inline playback gives more UI flexibility but requires manual lifecycle management.
Handle Playback Completion and Errors
Observe end notifications and item status so users get clear feedback.
For production code, remove observers on deinit and surface recoverable errors in UI.
Add Basic Playback Controls
For custom interfaces, connect play and pause actions to the same player instance and expose simple state updates for UI controls.
You can bind these methods to button taps in UIKit or SwiftUI wrappers. Keeping playback commands in one small controller class improves testability and reduces repeated state logic across views.
For long videos, also consider observing timeControlStatus to update loading indicators and playback buttons in sync with real player state during buffering events and intermittent network delays on device hardware in production apps.
Common Pitfalls
A common mistake is using wrong file path assumptions for bundled assets. Always resolve URLs through Bundle.main or FileManager.
Another issue is presenting player controller before setting player. Configure controller first, then present and play.
A third issue is forgetting target membership for local resource files, which makes bundled videos unavailable at runtime.
Summary
- Use
AVPlayerViewControllerfor quick and reliable local video playback. - Resolve bundled and documents file URLs with the correct API.
- Use
AVPlayerLayerfor inline playback layouts. - Observe completion events for better playback UX.
- Validate resource inclusion and path correctness before debugging playback.

