我目前有一个为我的视图控制器运行的插页式广告。问题是当广告未准备好时,我的应用程序会因错误而崩溃。如果有人可以帮助我解决以下问题,我将不胜感激!谢谢
视图控制器:问题是当广告未准备好时,应用会因错误而崩溃。
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
}
此外,如果有人有时间也看看这个。我想让广告多次投放。我知道插页式广告不允许这样做,为了解决这个问题,我实现了这个功能,但它不起作用。这是错误的吗?
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
interstitial = CreateAd()
}
答案 0 :(得分:0)
您不应从 CreateAd()
返回广告,应在调用 GADInterstitialAd.load(..)
的 completionHandler 时设置广告。
这应该是您的 createAd 函数(不返回任何内容):
var interstitial: GADInterstitialAd?
func createAd() {
GADInterstitialAd.load(withAdUnitID:"id ...",
request: GADRequest(),
completionHandler: { ad, error in
if let error = error {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
return
}
interstitial = ad
interstitial?.fullScreenContentDelegate = self
}
)
}
然后随时展示它,并在广告关闭后再次调用 createAd()