iOS 10 Video Playback using AVPlayer and AVPlayerViewController

From Techotopia
Revision as of 23:24, 8 November 2016 by Neil (Talk | contribs)

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 is provided by combining the AVFoundation AVPlayer and AVKit AVPlayerViewController classes.

This chapter presents an overview of video playback in iOS 10 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 a Security Exception for an HTTP Connection

In iOS 9, Apple tightened the level of security for external resources such as files on remote servers. This is referred to as App Transport Security (ATS) and, by default, access to HTTP resources are now blocked within iOS apps. Wherever possible, therefore, the more secure HTTPS protocol should be used instead of HTTP. In recognition of the fact that not all servers support HTTPS it is possible to add an exception to the Info.plist file of the app project. This can be configured on a general basis or declared for individual domains.

To demonstrate this exception process in action, the video file used in this example is stored on an HTTP based web server. To add an exception for this server, locate and select the Info.plist file and set the properties as outlined in the figure below:


Ios 9 app transport security.png

Figure 93-1


Alternatively, Ctrl-click on the Info.plist file in the Project Navigator panel, select Open As -> Source Code from the resulting menu and enter the following exception settings for the ebookfrenzy.com domain:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>ebookfrenzy.com</key>
    <dict>
      <key>NSIncludesSubdomains</key>
      <true/>
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

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 container constraints to the view with both offset values set to 0.

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 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 93 2:


Ios 8 avplayer ui.png

Figure 93-2


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 prepare(for segue:) 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let destination = segue.destination as!
                                AVPlayerViewController
        let url = URL(string:
                "http://www.ebookfrenzy.com/ios_book/movie/movie.mov")

            if let movieURL = url {
                destination.player = AVPlayer(url: movieURL)
            }
    }
.
.

The code in this above method begins by obtaining a reference to the destination view controller, in this case the AVPlayerViewController instance. A URL 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 93-3


Creating AVPlayerViewController Instance from Code

The example shown in this chapter used storyboard scenes and a transition to display an AVPlayerViewController instance. While 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 10 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