Search code examples
iosuiviewavplayeravplayerviewcontroller

Add AVPlayer subview to UIView


I am using the following code to create a vertical scrollview with paging enabled which works perfectly fine. Now I would like to add a subview of the type AVPlayer (?) to homeView, view2, view3. I can put setupCustomPlayer() in the initiateScrollView() function which works very well, too. However, it is not attached to any of the previously-mentioned views. If I try to add a subview using the function addSubview(anything) it tells me a UIView is expected. I need the UIViews as the vertical sliding feed is very important. Does someone know how to add it as a subview? The video is going to cover the entire screen and going to serve as kind of a background video one could say (if you would like to know)

Code:

func setupCustomPlayer() {

    print("check")

    AVPlayerVC.view.frame = self.view.frame
    AVPlayerVC.view.sizeToFit()
    AVPlayerVC.showsPlaybackControls = false
    self.view.addSubview(AVPlayerVC.view)

    let videoURL = NSURL(string: "http://URL")


    let player = AVPlayer(url: videoURL! as URL)
    AVPlayerVC.player = player
    AVPlayerVC.player?.play()
}

func initiateScrollView() {

    //create scrollView with paging enabled
    let scrollView = UIScrollView(frame: view.bounds)
    scrollView.isPagingEnabled = true
    view.addSubview(scrollView)

    //do not show vertical scroll indicator
    scrollView.showsVerticalScrollIndicator = false;

    //get page size
    let pageSize = view.bounds.size

    //individual views
    let homeView = UIView()
    homeView.backgroundColor = .green

    let view2 = UIView()
    view2.backgroundColor = .blue

    let view3 = UIView()
    view3.backgroundColor = .red

    //array with individual views
    let pagesViews = [homeView, view2, view3]

    //amount of views
    let numberOfPages = pagesViews.count

    //add subviews (pages)
    for (pageIndex, page) in pagesViews.enumerated(){
        page.frame = CGRect(origin: CGPoint(x:0 , y:CGFloat(pageIndex) * pageSize.height), size: pageSize)
        scrollView.addSubview(page)
    }

    //define size of scrollView
    scrollView.contentSize = CGSize(width: pageSize.width, height: pageSize.height * CGFloat(numberOfPages))

}

Solution

  • Could you try this?

    func setupCustomPlayer() {
    
        print("check")
        let player = AVPlayer(url: yourFileUrl)
        var playerLayer: AVPlayerLayer?
        playerLayer = AVPlayerLayer(player: player)
        playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        playerLayer!.frame = self.view.frame
        self.view.layer.addSublayer(playerLayer!)
    
        player.play()
    }