Search code examples
iosswiftadmobinterstitial

Admob interstitial ad delegate


I am trying to assign a delegate to admob interstitial ad so i can handle ad events.

The GADInterstitialDelegate implementing class:

class AdDelegate: NSObject, GADInterstitialDelegate
{
//Interstitial delegate
func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {
    println("interstitialDidFailToReceiveAdWithError:\(error.localizedDescription)")

}

func interstitialDidReceiveAd(ad: GADInterstitial!) {
    println("interstitialDidReceiveAd")

}

func interstitialWillDismissScreen(ad: GADInterstitial!) {
    println("interstitialWillDismissScreen")

}

func interstitialDidDismissScreen(ad: GADInterstitial!) {
    println("interstitialDidDismissScreen")
}

func interstitialWillLeaveApplication(ad: GADInterstitial!) {
    println("interstitialWillLeaveApplication")
}

func interstitialWillPresentScreen(ad: GADInterstitial!) {
    println("interstitialWillPresentScreen")
}

}

The assign of the delegate to the ad:

add.delegate = AdDelegate()

The problem is that the ad events are not fired inside the AdDelegate implementing class (the ad is shown properly) any idea why?

I cant implement the GADInterstitialDelegate in the same class as the assign to the ad object becasue the ad object is created in class func which give compiler error


Solution

  • GADInterstitial delegate is a weak stored property, so you should create a stored property in your class:

    var adDelegate : AdDelegate? // to store the delegate 
    
    func createInterstitial()->GADInterstitial {
        var interstitial = GADInterstitial()
        interstitial.adUnitID = "ca-app-pub-6938332798224330/6206234808";
        adDelegate = AdDelegate()
        interstitial.delegate = adDelegate //delegate is weak so we need to store the property
    
        return interstitial
    }
    

    Please look at the documentation to better understand how ARC works https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html