I am trying to make this button segue to a new ViewController once the user closes the interstitial ad. The segue code works without the ad code and the ad code works without the segue code. Whichever one is put first happens first, but I can't figure out how to get them to work together. You'll notice that I tried moving self.present...
to various places with no success (see noted out lines).
@IBAction func adButton(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myVC = storyboard.instantiateViewController(withIdentifier: "newVC")
//self.present(myVC, animated: true, completion: nil)
if (interstitial.isReady) {
interstitial.present(fromRootViewController: self)
interstitial = createAd()
//self.present(myVC, animated: true, completion: nil)
}
self.present(myVC, animated: true, completion: nil)
}
The interstitial
object has a delegate (GADInterstitialDelegate
) protocol that you can conform to in order to be notified when the ad has been dismissed. There are several delegate methods addressing the ad state which you can review in the documentation.
class ViewController:UIViewController, GADInterstitialDelegate {
override func viewDidLoad() {
super.viewDidLoad()
interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
interstitial.delegate = self
let request = GADRequest()
interstitial.load(request)
}
@IBAction func adButton(_ sender: UIButton) {
if (interstitial.isReady) {
interstitial.present(fromRootViewController: self)
} else {
self.present(myVC, animated: true, completion: nil)
}
}
//Tells the delegate the interstitial is to be animated off the screen.
func interstitialWillDismissScreen(_ ad: GADInterstitial) {
print("interstitialWillDismissScreen")
}
//Tells the delegate the interstitial had been animated off the screen.
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
print("interstitialDidDismissScreen")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myVC = storyboard.instantiateViewController(withIdentifier: "newVC")
self.present(myVC, animated: true, completion: nil)
}
}
Google Ads Docs: Interstitial Ads