How do I implement picture-in-picture in AVPlayerViewController?

Generated on 7/31/2024

1 search

To implement Picture-in-Picture (PiP) in AVPlayerViewController, you can leverage the AVKit framework, which provides built-in support for PiP. Here are the steps to enable and use PiP in your app:

  1. Enable PiP in AVPlayerViewController: Ensure that the allowsPictureInPicturePlayback property of your AVPlayerViewController instance is set to true.

    let playerViewController = AVPlayerViewController()
    playerViewController.allowsPictureInPicturePlayback = true
    
  2. Configure the AVPlayer: Set up your AVPlayer with the desired media content and assign it to the player property of your AVPlayerViewController.

    let player = AVPlayer(url: videoURL)
    playerViewController.player = player
    
  3. Present the AVPlayerViewController: Present the AVPlayerViewController in your app's view hierarchy.

    present(playerViewController, animated: true) {
        player.play()
    }
    
  4. Handle PiP Delegate Methods (Optional): Implement the AVPlayerViewControllerDelegate methods to handle PiP events, such as when PiP starts or stops.

    class ViewController: UIViewController, AVPlayerViewControllerDelegate {
        func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController) {
            // Handle PiP start
        }
    
        func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController) {
            // Handle PiP stop
        }
    
        func playerViewController(_ playerViewController: AVPlayerViewController, failedToStartPictureInPictureWithError error: Error) {
            // Handle PiP start failure
        }
    }
    
  5. Set the Delegate: Assign the delegate to your AVPlayerViewController instance.

    playerViewController.delegate = self
    

For more detailed information on using AVPlayerViewController and its capabilities, you can refer to the session Explore multiview video playback in visionOS from WWDC 2024. This session covers various aspects of AVPlayerViewController, including its integration with system features and enhancements for video viewing capabilities.