IOS 8 Video Playback using AVPlayer and AVPlayerViewController

From Techotopia
Revision as of 19:39, 10 May 2016 by Neil (Talk | contribs) (Text replacement - "<hr> <table border="0" cellspacing="0"> <tr>" to "<!-- Ezoic - BottomOfPage - bottom_of_page --> <div id="ezoic-pub-ad-placeholder-114"></div> <!-- End Ezoic - BottomOfPage - bottom_of_page --> <hr> <table border="0" cellspacing="0"> <tr>")

Jump to: navigation, search
PreviousTable of ContentsNext
An Example Swift iOS 8 iPhone Camera ApplicationPlaying Audio on iOS 8 using AVAudioPlayer


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


Whilst the iPhone 3GS model introduced support for recording videos using the built in camera, all iPhone and iPad models and iOS versions have included support for video playback. Video playback support in iOS 8 is provided by combining the AVFoundation AVPlayer and AVKit AVPlayerViewController classes.

This chapter presents an overview of video playback in iOS 8 using these two classes followed by a step by step example.


Contents


The AVPlayer and AVPlayerViewController Classes

The sole purpose of the AVPlayer class is to play media content. An AVPlayer instance is initialized with the URL of the media to be played (either a path to a local file on the device or the URL of network based media). Playback can be directed to a device screen or, in the case of external playback mode, via AirPlay or an HDMI/VGA cable connection to an external screen.

The AVKit Player View Controller (AVPlayerViewController) class provides a view controller environment through which AVPlayer video is displayed to the user together with a number of controls that enable the user to manage the playback experience. Playback may also be controlled from within the application code by calling the play and pause methods of the AVPlayer instance.

The iOS Movie Player Example Application

The objective of the remainder of this chapter is to create a simple application that will play back a video when a button is pressed. The video will be streamed over the internet from a movie file located on a web server.

Begin by launching Xcode and creating a new iOS application project based on the Single View Application template configured for the Swift language and Universal devices, naming the product AVPlayerDemo.


Adding the AVKit Framework to the Xcode Project

Once the new project has been created, the first step is to make sure the AVKit Framework is included in the project. Failure to add this framework will result in the application crashing at runtime.

To add the AVKit framework, select the AVPlayerDemo target located at the top of the project navigator panel. In the center pane, select the Build Phases tab and unfold the Link Binary With Libraries panel. Click on the ‘+’ button to display a list of existing frameworks, locate and select AVKit.framework and click the Add button. The AVKit.framework will now appear in the frameworks list along with any other frameworks already included in the project.

Designing the User Interface

Select the Main.storyboard file and display the Object Library (View -> Utilities -> Show Object Library). Drag a single Button instance to the view window and change the text on the button to “Play Movie”. With the button selected in the storyboard canvas, display the Auto Layout Align menu and add both horizontal and vertical Center in Container constraints to the view.

From the Object Library panel, locate the AVKit Player View Controller object and drag and drop it onto the storyboard to the right of the existing view controller. Ctrl-click on the button in the first view controller and drag the resulting line to the second AVKit Player View Controller. Release the line and select show from the segue selection menu. On completion of these tasks, the storyboard should resemble that of Figure 87-1:


Ios 8 avplayer ui.png

Figure 87-1

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Initializing Video Playback

When the “Play Movie” button is tapped by the user the application will perform a segue to the AVPlayerViewController scene. Verify that this works by running the application and selecting the button. The AVPlayerViewController will appear and display the video playback controls but as yet no AVPlayer has been configured to play video content. This can be achieved by implementing the prepareForSegue method within the ViewController.swift file as follows, the code for which relies on the AVKit and AVFoundation frameworks having been imported:

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {
.
.
.
    override func prepareForSegue(segue: UIStoryboardSegue, 
		sender: AnyObject?) {
        let destination = segue.destinationViewController as! 
				AVPlayerViewController
        let url = NSURL(string: 
		"http://www.ebookfrenzy.com/ios_book/movie/movie.mov")
        destination.player = AVPlayer(URL: url)
    }
.
.

The code in this above method begins by obtaining a reference to the destination view controller, in this case the AVPlayerViewController instance. An NSURL object is then initialized with the URL of a web based video file. Finally a new AVPlayer instance is created, initialized with the video URL and assigned to the player property of the AVPlayerViewController object.

Running the application once again should cause the video to be available for playback within the player view controller scene.

Build and Run the Application

With the design and coding phases complete, all that remains is to build and run the application. Click on the run button located in the toolbar of the main Xcode project window. Assuming that no errors occur, the application should launch within the iOS Simulator or device. Once loaded, touching the Play Movie button should launch the movie player in full screen mode and playback should automatically begin:

Ios 8 avplyer example running.png

Figure 87-2

Creating AVPlayerViewController Instance from Code

The example shown in this chapter used storyboard scenes and a transition to display an AVPlayerViewController instance. Whilst this is a quick approach to working with the AVPlayerViewController and AVPlayer classes, the same result may also be achieved directly by writing code within the application. The following code fragment, for example, initializes and plays video within an application using these two classes without the use of a storyboard scene:

let player = AVPlayer(URL: url)
let playerController = AVPlayerViewController()

playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame

player.play()

Summary

The basic classes needed to play back video from within an iOS 8 application are provided by the AVFoundation and AVKit frameworks. The purpose of the AVPlayer class is to facilitate the playback of video media files. The AVPlayerViewController class provides a quick and easy way to embed an AVPlayer instance into a view controller environment together with a set of standard on-screen playback controls.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
An Example Swift iOS 8 iPhone Camera ApplicationPlaying Audio on iOS 8 using AVAudioPlayer