Search code examples
swiftvideoavfoundationmedia-playeravplayer

Video doesn't play full screen in a given view in swift. Need help fixing it


I have a view that plays video in app. The constraints given are correct but some how in devices like iPhone 11, iPhone 11 pro the view leaves some space at trailing end. Adding screenshots for reference.

Issue - Simulator: iPhone 11 pro max Constraints Screenshot *Need help fixing the video display to full view.

Constraints: Align Trailing - Safe area Align Top - Safe area Align Leading - Safe area Height Equals - 150

Code:

import UIKit
import AVFoundation
    
class VideoViewController: UIViewController {
@IBOutlet weak var videoView: UIView!  
    
var player: AVQueuePlayer!
var playerItem: AVPlayerItem!
var playerLooper: AVPlayerLooper!
    
override func viewDidLoad() {
   super.viewDidLoad()
    videoView()
}

func videoViewForLogin() {
//video 
 guard let url = Bundle.main.url(forResource: "splashpanoslice", withExtension: "mp4") else {return}
let playerPath = AVPlayer(url: url)
player = AVQueuePlayer()
let playerLayer = AVPlayerLayer(player: player)
playerItem = AVPlayerItem(url: url)
let duration = Int64( ( (Float64(CMTimeGetSeconds(AVAsset(url: url).duration)) *  10.0) - 1) / 10.0 )
playerLayer.frame = videoView.bounds
playerLooper = AVPlayerLooper(player: player, templateItem: playerItem,                                          timeRange: CMTimeRange(start: CMTime.zero, end: CMTimeMake(value: duration, timescale: 1)) )
playerLayer.videoGravity = .resizeAspectFill
         videoView.layer.insertSublayer(playerLayer, at: 1)
player.play()
  }
}

The function code is taken from a reference - How do i make a looping video in swift


Solution

  • Since you're using frames, I think you should try moving layout code later than viewDidLoad(). Perhaps, viewDidLayoutSubviews(), when the view size is determined and also invalidated when displaying parameters are changed (e.g. the screen orientation has changed).