In iOS14, apple opened up pin-in-picture support on the mobile end, which allows you to play videos even when your app is out of the foreground. In essence, the opening of picture-in-picture still depends on the system player, while UI and animation are provided by the system native, so the space for customization is very small.

The official documentation

For specific usage, it is recommended to read the official documents first. The official documents are as follows

  1. Built using the system’s AVPlayerViewController
  2. Using the system of AVPlayer + AVPictureInPictureController build

demo

After reading the official documentation, take a look at the full implementation. I don’t want to post code snippets here. demo

Simple summary

It is very simple to use, the system is highly customized, no technical content

  1. Creating system PlayerAVPlayer
  2. Create render targetAVPlayerLayer
  3. Create the picture-in-picture controllerAVPictureInPictureController
  4. Turn on picture in picture

Fill in the pit

The official documentation is simple and clear, but in practice there will sometimes be picture-in-picture open failures without any callbacks. In this case, you need to check whether your code meets the following points

  1. judgeisPictureInPicturePossible

AVPictureInPictureController not create good can be used immediately, need through isPictureInPicturePossible properties determine the state. If isPictureInPicturePossible = = NO direct call startPictureInPicture attempt to open the picture in picture, not only have NO effect, but don’t get any callback

  1. Player for renderingview,layerBe sure to join the hierarchy correctly

If the business uses the system player, there is generally no problem here because the player is displayed correctly. But if the business uses a custom player and also wants picture-in-picture capability, a hidden system player is often created to host the picture-in-picture capability. Care should be taken to ensure that the views and layers used for rendering are properly added to the hierarchy, otherwise, again, there is no perceived failure

  1. Strong holdAVPictureInPictureController

Also mentioned that the official document, add here, when calling stopPictureInPicture closed picture in picture, don’t immediately release AVPictureInPictureController, otherwise you will see a picture in picture anomaly.

  1. Only full-screen players can automatically turn on picture-in-picture while cutting background

Here “full screen”, after testing, as long as the width or height of the video to fill the screen. For example, the 16:9 playerView in the demo does not fill the entire screen, and can also automatically start picture-in-picture