We understand that AVPlayerViewController is a ViewController and like all view controllers, it takes full view when it’s either pushed or presented. But it can also be rendered as a subview with a custom frame by adding it as a child viewcontroller. The approach is pretty straightforward. The code given below plays a video from a URL in a custom frame.
import UIKit import AVKit class ViewController: UIViewController { @IBOutlet weak var videoPlayer: UIView! //Just for frame var playerViewController: AVPlayerViewController? override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { guard let videoURL = URL(string: "https://www.rmp-streaming.com/media/big-buck-bunny-360p.mp4") else { return } //1. creating player let player = AVPlayer(url: videoURL) playerViewController = AVPlayerViewController() playerViewController?.videoGravity = .resizeAspectFill playerViewController?.player = player //2.Adding as child viewcontroller self.addChild(playerViewController!) //3. Adding subview self.view.addSubview(playerViewController!.view) //4. Custom frame set playerViewController?.view.frame = self.videoPlayer.frame //5. play video playerViewController?.player?.play() } }
It should be noted that all controls might not show if we are rendering AVPlayerViewController in a custom frame. Hope this helps cheers!!!