Search code examples
swiftavfoundationavplayer

Unexpectedly found nil while unwrapping an Optional value, while trying to play video


I am using AVFoundation kit to play a local video

I tried this code:

import UIKit
import AVFoundation

class ViewController: UIViewController {

var player: AVPlayer?

@IBOutlet weak var videoViewContainer: UIView!


override func viewDidLoad() {
    super.viewDidLoad()
    initializeVideoPlayerWithVideo()
}

func initializeVideoPlayerWithVideo() {

    // get the path string for the video from assets
    let videoString:String? = Bundle.main.path(forResource: "Air Bike", ofType: "mov")
    guard let unwrappedVideoPath = videoString else {return}

    // convert the path string to a url
    let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)

    // initialize the video player with the url
    self.player = AVPlayer(url: videoUrl)

    // create a video layer for the player
    let layer: AVPlayerLayer = AVPlayerLayer(player: player)

    // make the layer the same size as the container view
    layer.frame = videoViewContainer.bounds

    // make the video fill the layer as much as possible while keeping its aspect size
    layer.videoGravity = AVLayerVideoGravity.resizeAspectFill

    // add the layer to the container view
    videoViewContainer.layer.addSublayer(layer)
}


@IBAction func playVideoButtonTapped(_ sender: UIButton) {
    // play the video if the player is initialized
    player?.play()
}
}

I've trying a few different approaches and I'm still getting the same error message can someone How can I resolve this issue?


Solution

  • func initializeVideoPlayerWithVideo() {
    
        guard let path = Bundle.main.path(forResource: "jagdeep", ofType:".MOV") else {
            debugPrint("video.m4v not found")
            return
        }
    
        self.player = AVPlayer(url: URL(fileURLWithPath: path))
    
        // create a video layer for the player
        let layer: AVPlayerLayer = AVPlayerLayer(player: player)
    
        // make the layer the same size as the container view
        layer.frame = videoViewContainer.bounds
    
        // make the video fill the layer as much as possible while keeping its aspect size
        layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
    
        // add the layer to the container view
        videoViewContainer.layer.addSublayer(layer)
    
        player?.play()
    }
    

    HERE IS MY VIDEO NAME jagdeep and type .MOV AND its working on my side. It's problem in your code where you using type mov. I just drag a video name jagdeep.MOV to my project and use Your code. its ok enter image description here