You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AdMob广告展示完成后如何自动切换至其他ViewController

解决AdMob插屏广告展示完成后自动跳转ViewController的问题

你的代码问题在于:调用广告展示后立刻执行了ViewController跳转,但广告展示会阻塞当前的present操作,导致跳转逻辑无法正常触发,必须等广告关闭后再次点击按钮才会执行。要实现广告关闭后自动跳转,需要利用AdMob的广告回调代理方法,在广告关闭后再执行跳转逻辑。

步骤1:让ViewController遵守AdMob全屏内容代理协议

确保你的ViewController实现GADFullScreenContentDelegate协议(针对新版GADInterstitialAd):

class YourViewController: UIViewController, GADFullScreenContentDelegate {
    // 声明插屏广告对象
    var interstitial: GADInterstitialAd?
    
    // 你的其他代码...
}

步骤2:抽离跳转逻辑为单独方法

把重复的跳转代码封装成私有方法,避免冗余:

private func navigateToExamSimulator() {
    let examVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ExamSimulator") as! ExamSimulatorViewController
    examVC.status = "ExamSimulator"
    examVC.modalPresentationStyle = .fullScreen
    present(examVC, animated: true)
}

步骤3:修改广告展示方法,设置代理并处理不同场景

更新doSomething方法,给广告设置代理,并处理广告未准备好、用户已购买的直接跳转场景:

@IBAction func doSomething(_ sender: Any) {
    let save = UserDefaults.standard
    if save.value(forKey: "Purchased") == nil {
        if let interstitialAd = interstitial {
            // 设置广告代理,监听关闭事件
            interstitialAd.fullScreenContentDelegate = self
            interstitialAd.present(fromRootViewController: self)
        } else {
            print("Ad wasn't ready")
            // 广告未准备好,直接跳转
            navigateToExamSimulator()
        }
    } else {
        print("PAID ADS OFF")
        // 用户已购买,直接跳转
        navigateToExamSimulator()
    }
}

步骤4:实现广告关闭的代理方法

在代理方法中处理广告关闭、展示失败后的跳转:

// 广告关闭后触发跳转
func interstitialAdDidDismissScreen(_ ad: GADInterstitialAd) {
    navigateToExamSimulator()
    // 可选:重新加载广告,供下次使用
    loadInterstitialAd()
}

// 广告展示失败时,也执行跳转
func interstitialAd(_ ad: GADInterstitialAd, didFailToPresentFullScreenContentWithError error: Error) {
    print("Ad presentation failed: \(error.localizedDescription)")
    navigateToExamSimulator()
}

步骤5:简化按钮点击方法

修改openExamSimulator,只需要调用广告展示方法即可:

@IBAction func openExamSimulator(_ sender: Any) {
    doSomething(sender)
}

针对旧版GADInterstitial的兼容

如果你使用的是旧版GADInterstitial,代理方法需要替换为:

func interstitialDidDismissScreen(_ ad: GADInterstitial) {
    navigateToExamSimulator()
}

func interstitial(_ ad: GADInterstitial, didFailToPresentScreenWithError error: Error) {
    print("Ad presentation failed: \(error.localizedDescription)")
    navigateToExamSimulator()
}

内容的提问来源于stack exchange,提问作者Alex Izmestyev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 07:15:33