Do not load Interstitial admob in Swift

2

Good, what I want to do is that when a button is pressed, a view is displayed with advertising to be more accurate AdMob's Interstitial. I have a problem since the button is in a view and when I click it, this% fatal error: unexpectedly found nil while unwrapping an Optional value error occurs and the application stops working.

I leave the code.

var interstitial: GADInterstitial!
func createAndLoadAd() -> GADInterstitial {
    let ad = GADInterstitial(adUnitID: "XXX-XXX-XXX")

    let request = GADRequest()

    request.testDevices = ["XXXXXXXXXXXXX"]
    ad.loadRequest(request)

    return ad
}

func MuestraPublicidad() {
        if (self.interstitial.isReady)
        {
            self.interstitial.presentFromRootViewController(self)
            self.interstitial = self.createAndLoadAd()
        }
}

In The UIview I've done it in the following way

let VistaPrincipal = ViewController()
VistaPrincipal.MuestraPublicidad()
    
asked by Bogdan 06.02.2016 в 04:11
source

1 answer

1

You are trying to present the interstitial before creating it, that is, change this:

self.interstitial.presentFromRootViewController(self)
self.interstitial = self.createAndLoadAd()

for this

self.interstitial = self.createAndLoadAd()
self.interstitial.presentFromRootViewController(self)

It should work, since var interstitial: GADInterstitial! does not exist when you try to display it

Update 1

It may also be that you should check if var interstitial: GADInterstitial! exists. To do so, you can modify the code so that:

if let inter = self.interstitial { // Nos aseguramos que exista
    inter.presentFromRootViewController(self)
}
    
answered by 06.02.2016 в 11:45