'using avplayerkit issue while playing video black screen coming

hello i am new to swift and i am using AVPlayerViewController for plaing video from my url but issue is that i am not able to load video only black screen showing let me show my code

Code

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    @IBOutlet weak var viewPlayer: UIView!
    var player: AVPlayer!
    var avpController = AVPlayerViewController()
    var url = "https://www.youtube.com/watch?v=HsQvAnCGxzY"
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = URL(string: self.url)

        player = AVPlayer(url: url!)

        avpController.player = player

        avpController.view.frame.size.height = viewPlayer.frame.size.height

        avpController.view.frame.size.width = viewPlayer.frame.size.width

        self.viewPlayer.addSubview(avpController.view)
        // Do any additional setup after loading the view, typically from a nib.
    }

}

Please refer code given and tell me where i am done wrong so that i can able to play video Thanks In Advance



Solution 1:[1]

Actually Its problem of URL . AVPlayer never supports YouTube video. It supports mp4 format.

Solution 2:[2]

If you want to play a video in your ViewController, you have to use AVPlayerLayer. You have to implement player controllers yourself.

override func viewDidLoad() {
    super.viewDidLoad()
    
    // creating video url
    guard let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") else {
        return
    }
    
    // create AVPlayer
    let player = AVPlayer(url: videoURL)
    
    // setup AVPlayerLayer
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.bounds
    self.view.layer.addSublayer(playerLayer)
    
    // start playing
    player.play()
}

Otherwise use AVPlayerViewController. Instead of using its view present the viewController itself.

override func viewDidLoad() {

    super.viewDidLoad()

    // creating video url
    guard let videoURL = URL(string: "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4") else {
        return
    }
    
    // setup AVPlayer and AVPlayerViewController
    let player = AVPlayer(url: videoURL)
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player

}

override func viewDidAppear(_ animated: Bool) {
    
    // presenting playerViewController only after the viewControllers view was added to a view hierarchy.
    
    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Niki Mehta
Solution 2 Sreekuttan