Topics

#25: Picture in Picture 📺

Topics

One of the coolest new features in iOS 9 is the new Picture in Picture functionality on iPad. This lets users watch video content from an app even while it's in the background.

To support it in our app, we'll first make sure you set the Playback audio category in our application(application:didFinishLaunchingWithOptions:) function:

do {
  try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch { }

Then we'll use AVPlayerViewController to play video content. Picture in Picture mode will automatically kick-in if our app enters background but only if: 1.) our player is full screen, 2.) video content is playing in it, and 3.) Picture in Picture is supported on the device.

Next we'll implement this wonderfully long delegate method to restore our player UI when the user returns from Picture in Picture mode:

func playerViewController(playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: (Bool) -> Void) {
  navigationController?.presentViewController(playerViewController, animated: true) {
    completionHandler(true)
  }
}

More About PIP

  • If we need to support a generic AVPlayerLayer, AVKit also includes a new AVPictureInPictureController.

  • We also get PIP for free in WKWebView assuming our app has the Playback audio session category set.