Charles
Charles

Reputation: 31

IOS Custom UIViewController Error

In my login screen of my Ios app I am trying to display a video. I saw on stack overflow a great example on how to do such thing. I tried the code out for myself and ran into an error. I was going to comment my error on the original post but my account did not have enough reputation to do so. My code when I run on my simulated device returns to me an error that says:

fatal error: unexpectedly found nil while unwrapping an Optional value

(lldb)

I managed to track down there error using breakpoints to line 12 which is avPlayer = AVPlayer(url: video!)

Though here is my full code:

import AVFoundation
import UIKit

class VideoBackgroundController: UIViewController {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false

override func viewDidLoad() {
    let video = Bundle.main.url(forResource:"space", withExtension: "mp4")
    //This is where my the error happens
    avPlayer = AVPlayer(url: video!)
    avPlayerLayer = AVPlayerLayer(player: avPlayer)
    avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    avPlayer.volume = 0
    avPlayer.actionAtItemEnd = .none

    avPlayerLayer.frame = view.layer.bounds
    view.backgroundColor = .clear
    view.layer.insertSublayer(avPlayerLayer, at: 0)

    NotificationCenter.default.addObserver(self,
                                           selector: #selector(playerItemDidReachEnd(notification:)),
                                           name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                           object: avPlayer.currentItem)
}

func playerItemDidReachEnd(notification: Notification) {
    let p: AVPlayerItem = notification.object as! AVPlayerItem
    p.seek(to: kCMTimeZero)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    avPlayer.play()
    paused = false
}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    avPlayer.pause()
    paused = true
}
}

And I do have a mp4 video named "space" in my project files.

This is my project tree with my video

Any explanation to how or why this is happening and what actions I can take to fix this issue would be greatly appreciated.

Upvotes: 0

Views: 132

Answers (2)

Myaaoonn
Myaaoonn

Reputation: 997

I have checked and your code is running fine.

Just check that, the video should be under in your "Copy bundle Resources" of "Build Phases" tab in Target .

If it is not there , Please add the same as in below screenshots.

Should be in Build Phases tab

Upvotes: 1

Lalit kumar
Lalit kumar

Reputation: 2207

You are assigning non optional value of video. Make it optional, ? Swift means – It can have a value, but it can also be nil. It is defined by “?”.Please look below code

avPlayer = AVPlayer(url: video?)
if avPlayer != nil
{ // Video url is not empty
}
else
{ // It is empty
}

Upvotes: 0

Related Questions