Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add AVPlayer to UIView in ViewController

I my UIViewController I have an outlet to UIView, where I would like to display video using external links. In this case I try to create AVPlayerLayer and add it to my UIView outlet.

My code looks like that:

class VievController: UICollectionViewController {
    @IBOutlet weak var playerView: UIView!

    override func viewDidLoad(){
            let playerItem = AVPlayerItem(URL: NSURL(string: ("https://www.youtube.com/watch?v=_yE_XgoWBso"))!)
            let avPlayer = AVPlayer(playerItem: playerItem)
            let playerLayer = AVPlayerLayer(player: avPlayer)
            playerLayer.frame = playerView.bounds
            playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            playerView.layer.addSublayer(playerLayer)
            avPlayer.play()
    }
}//end class

I don't know why I don't see video on my UIVIew outlet - nothing happened. Do you have any suggestion what should I fix?

like image 250
PiterPan Avatar asked Jun 24 '16 10:06

PiterPan


2 Answers

Below code help you to solve the issue

Adjust the frame according to your needs

- (void)viewDidLoad
{
   [super viewDidLoad];
   NSError *setCategoryError = nil;
  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: &setCategoryError];
  NSString *urlString=[NSString stringWithFormat:@"%@",@"http://www.youtube.com/watch?v=zPP6lXaL7KA&feature=youtube_gdata_player"];
  AVAsset *asset = [AVAsset assetWithURL:[NSURL urlWithString:urlString]];
  avPlayerItem = [[AVPlayerItem alloc]initWithAsset:asset];
  self.songPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
  self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer: self.songPlayer];
  self.avPlayerLayer.frame = self.view.layer.bounds;
  UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds];
  [newView.layer addSublayer:avPlayerLayer];
  [self.view addSubview:newView];
  [ self.songPlayer play];
}
like image 121
Nattudurai Avatar answered Sep 18 '22 21:09

Nattudurai


Unfortunately, you cannot use AVPlayer to play YouTube, Vimeo, etc. For that purpose you'll have to use UIWebView.

like image 45
SebyDrax Avatar answered Sep 19 '22 21:09

SebyDrax