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?
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];
}