How to play video with AVPlayerViewController (AVKit) in Swift
Swift 3.x - 5.x
Necessary: import AVKit, import AVFoundation
AVFoundation framework is needed even if you use AVPlayer
If you want to use AVPlayerViewController:
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")let player = AVPlayer(url: videoURL!)let playerViewController = AVPlayerViewController()playerViewController.player = playerself.present(playerViewController, animated: true) { playerViewController.player!.play()}
or just AVPlayer:
let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")let player = AVPlayer(url: videoURL!)let playerLayer = AVPlayerLayer(player: player)playerLayer.frame = self.view.boundsself.view.layer.addSublayer(playerLayer)player.play()
It's better to put this code into the method: override func viewDidAppear(_ animated: Bool) or somewhere after.
Objective-C
AVPlayerViewController:
NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];AVPlayer *player = [AVPlayer playerWithURL:videoURL];AVPlayerViewController *playerViewController = [AVPlayerViewController new];playerViewController.player = player;[self presentViewController:playerViewController animated:YES completion:^{ [playerViewController.player play];}];
or just AVPlayer:
NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];AVPlayer *player = [AVPlayer playerWithURL:videoURL];AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];playerLayer.frame = self.view.bounds;[self.view.layer addSublayer:playerLayer];[player play];
Try this, definitely works for Swift 2.0
let player = AVPlayer(URL: url) let playerController = AVPlayerViewController() playerController.player = player self.addChildViewController(playerController) self.view.addSubview(playerController.view) playerController.view.frame = self.view.frame player.play()
Try This
var player:AVPlayer!var avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player)avPlayerLayer.frame = CGRectMake(your frame)self.view.layer .addSublayer(avPlayerLayer)var steamingURL:NSURL = NSURL(string:playerURL)player = AVPlayer(URL: steamingURL)player.play()