Search code examples
iosswiftavfoundationavplayeravplayerlayer

AVPlayerLayer is nil


I'm capturing a video, after the capture is done I'm trying to preview the captured video on my AVPlayerLayer.

After capturing the video, I do save the url to DocumentsDirectory. This url is also saved in AVCaptureFileOutputRecordingDelegate's "didFinishRecordingTo" function as "outputFileURL".

I wrote the code below to didFinishRecordingTo function.

Created an AVplayer with the relative url, created an AVPlayerLayer as "previewLayer" with corresponded AVPlayer. But still I'm printing the line below which says "preview Layer nil" I've also tried print(previewLayer) but it says that it is nil.

Why this might be happening?

Appreciate it

 private var previewLayer : AVPlayerLayer?

   let player = AVPlayer(url: outputFileURL)
    
    previewLayer? = AVPlayerLayer(player: player)
    previewLayer?.videoGravity = .resizeAspectFill
    previewLayer?.frame = cameraView.bounds
    print(previewLayer)
    guard let previewLayer = previewLayer else {
        print("preview Layer nil")
        return
    }
    
    cameraView.layer.addSublayer(previewLayer)
    previewLayer.player?.play()
    recordButton.isHidden = true

Solution

  • Remove ? from previewLayer? ( only in below line ) as it will make the line useless that defaults to

    previewLayer? = AVPlayerLayer(player: player)
    
    nil = AVPlayerLayer(player: player)
    

    That leaves previewLayer nil , So make it

    previewLayer = AVPlayerLayer(player: player)