iOS swift , video output not centering inside the UIView

So I got this video playing inside a sublayer of the view , but the video keeps popping underneath the UIView not inside of it any solution ?

import UIKit
import AVKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController {

    var player : AVPlayer? = nil
    var playerLayer : AVPlayerLayer? = nil
    var asset : AVAsset? = nil
    var playerItem: AVPlayerItem? = nil

    @IBOutlet weak var videoView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let videoURLWithPath = "http://selevision9890-i.akamaihd.net/hls/live/219323/98906/1.m3u8"
        let videoURL = NSURL(string: videoURLWithPath)
        asset = AVAsset(URL: videoURL!) as AVAsset
        playerItem = AVPlayerItem(asset: asset!)
        videoView.frame = self.view.frame
        player = AVPlayer(playerItem: self.playerItem!)
        playerLayer = AVPlayerLayer(player: self.player)
        playerLayer!.frame = videoView.frame
        videoView.layer.addSublayer(self.playerLayer!)

        player!.play()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

normal view:

ScreenShot

(from here: http://prnt.sc/e33dhf)

rotated view:

ScreenShot

(from here: http://prnt.sc/e33djs)


Solution 1:

Move this code into viewDidAppear or viewWillAppear - in viewDidLoad the frames are not correct yet. The view is resized to fit the screen size after viewDidLoad.

Solution 2:

Set PlayerLayer videogravity

let videoURLWithPath = "http://selevision9890-i.akamaihd.net/hls/live/219323/98906/1.m3u8"
let videoURL = NSURL(string: videoURLWithPath)
playerItem = AVPlayerItem(url: videoURL! as URL)
player = AVPlayer(playerItem: self.playerItem!)
playerLayer = AVPlayerLayer(player: self.player)
playerLayer.frame =  videoView.frame
playerLayer.backgroundColor = UIColor.black.cgColor
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
videoView.layer.addSublayer(self.playerLayer!)
player!.play()

Solution 3:

I had similiar problem. I went with subclassing UIView like this:

import UIKit

class VideoPlayerView: UIView {
var playerLayer: CALayer?

override func layoutSublayersOfLayer(layer: CALayer) {
    super.layoutSublayersOfLayer(layer)
    playerLayer?.frame = self.bounds
  }
}

and use it for setting up a video like this:

@IBOutlet weak var videoPlayer: VideoPlayerView!

func setupVideoOnView() {
    var player = AVPlayer(URL: mediaURL! as NSURL)
    let playerLayer = AVPlayerLayer(player: player)

    playerLayer.frame = self.videoPlayer.bounds
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.videoPlayer.layer.addSublayer(playerLayer)
    self.videoPlayer.playerLayer = playerLayer

}

That did a trick with wrong frame.