如何解决广告未就绪时出现插页式广告错误 - Swift
我目前有一个为我的视图控制器运行的插页式广告。问题是当广告未准备好时,我的应用程序会因错误而崩溃。如果有人可以帮助我解决以下问题,我将不胜感激!谢谢
视图控制器:问题是当广告未准备好时,应用会因错误而崩溃。
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,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()
}
解决方法
您不应从 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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。