I currently have an interstitial ad running for my viewcontroller. The issue is that when the ad is not ready, my app crashes with the error. If someone could help me with the following problems, I would appreciate it heaps! Thank you
View Controller : Issue being when the ad is not ready, app crashes with the error.
class JournalViewController: UIViewController, GADFullScreenContentDelegate {
var interstitial: GADInterstitialAd!
override func viewDidLoad() {
super.viewDidLoad()
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID:"id ...",
request: request,
completionHandler: { [self] ad, error in
if let error = error {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
return
}
interstitial = ad
interstitial?.fullScreenContentDelegate = self
}
)
let randomTime = Double(arc4random() + 20).truncatingRemainder(dividingBy: 60.0)
Timer.scheduledTimer(timeInterval: randomTime, target: self, selector: #selector(ViewController.CreateAd), userInfo: nil, repeats: false)
}
@objc func CreateAd() -> GADInterstitialAd {
if interstitial != nil {
interstitial.present(fromRootViewController: self)
let randomTime = Double(arc4random() + 20).truncatingRemainder(dividingBy: 60.0)
Timer.scheduledTimer(timeInterval: randomTime, target: self, selector: #selector(ViewController.CreateAd), userInfo: nil, repeats: false)
} else {
print("Ad not ready") // Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee788bff8)
interstitial = CreateAd()
}
return interstitial
}
Furthermore, if someone has time to also look at this. I want to have the ad run multiple times. I understand interstitial ads do not allow this and to combat this I implemented this function but it does not work. Is this incorrect?
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
interstitial = CreateAd()
}