Create a simple video playback app with built-in controls.
Framework
- AVFoundation
Overview
Using AVKit and AVFoundation, you can quickly create a simple video playback app.
Set Up the Audio Session
You use an audio session to communicate to the system how you intend to use audio in your app. The audio session acts as an intermediary between your app and the operating system—and, in turn, the underlying audio hardware. Configure the audio session to give your app the audio behavior expected of a media playback app.
Use
import AVFoundation
to add the AVFoundation framework to theApp
class.Delegate .swift In the
application(_:
method, retrieve the shared instance of the audio session and set the app’s audio session category todid Finish Launching With Options:) playback
and mode tomovie
.Playback
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playback, mode: .moviePlayback)
}
catch {
print("Setting category to AVAudioSessionCategoryPlayback failed.")
}
return true
}
Set Up and Configure the User Interface
After configuring your app’s audio session, you need to create the user interface for the player.
Open the
Main
file. In the Library’s search field, type.storyboard button
to find theButton
object.Drag the
Button
object into the View Controller Scene’s view and give it the title Play Video.Add alignment constraints to center the button both horizontally and vertically.

Implement Playback Behavior
Now that you have created the user interface, it’s time to add the code required to play a video.
In the Project Navigator, select the
Main
file and open the assistant editor..storyboard Control-drag from the Play Video button to the
View
class to add a newController .swift @IBAction
method calledplay
.Video Close the assistant editor and select the
View
class in the Project Navigator. Above the class definition, import the AVKit and AVFoundation frameworks.Controller .swift In the
play
method, add the following implementation:Video
@IBAction func playVideo(_ sender: UIButton) {
guard let url = URL(string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_adv_example_hevc/master.m3u8") else {
return
}
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: url)
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
present(controller, animated: true) {
player.play()
}
}
Your app is complete, and you can run it in the Simulator or on your iOS or tvOS device.