I keep getting this error "unexpectedly found nil while unwrapping an Optional value" Why?

338 views Asked by At

Im adding these StartApp interstitial ads and I keep getting an error when I call this function thats in my GameScene. If I call it in my GameViewController it works perfectly and I get no errors but its not working in my GameScene. How would I fix this. Thanks!

//This is the fuction that gives the error.

self.viewController.startAppAd!.loadAdWithDelegate(viewController.self)

//GameViewController.swift

class GameViewController: UIViewController, STADelegateProtocol  {

    var startAppAd: STAStartAppAd?

    override func viewDidLoad() {
        super.viewDidLoad()

        startAppAd = STAStartAppAd()

        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
        // Configure the view.
        let skView = self.view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true
    }


    // StartApp Ad loaded successfully
    func didLoadAd(ad: STAAbstractAd) {
        println("StartApp Ad had been loaded successfully")
        startAppAd!.showAd()
    }
}

//GameScene.swift
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    var touch: UITouch = touches.first as! UITouch
    var location = touch.locationInNode(self)
    var node = self.nodeAtPoint(location)

    if node.name == "levelone" {

    self.viewController.startAppAd!.loadAdWithDelegate(viewController.self)
}
2

There are 2 answers

5
Warren Burton On BEST ANSWER

GameViewController creates the GameScene during viewDidLoad but you are never assigning it to the GameScene for referencing

You say you have var viewController = GameViewController() in GameScene but thats not the same instance which created the scene in the first place.

You can add this to your viewDidLoad

scene.viewController = self to ensure that the instance with an non-nil startAppAd object is the one you are referencing.

0
Tomas Camin On

You're force unwrapping startAppAd (using the ! operator) which tells the compiler “I know that this optional definitely has a value; please use it.”. However in your code startAppAd is presumedly nil. Therefore the crash.

I suggest you take a basic tour and read Apple's "Swift Programming Language"