【问题标题】:How to implement AdMob Open Ad in a SwiftUI project with SwiftUI App Cycle?如何使用 SwiftUI App Cycle 在 SwiftUI 项目中实现 AdMob Open Ad?
【发布时间】:2021-04-28 11:50:36
【问题描述】:

我正在尝试使用 Google 的文档:https://developers.google.com/admob/ios/app-open-ads 在 SwiftUI 项目中实施 AdMob 开放式广告。问题是文档完全是使用 AppDelegate 编写的。

我尝试通过在@main 上方添加具有此方法的 AppDelegate 类来实现打开的广告,但它根本不起作用。没有错误,也没有广告。

class AppDelegate: UIResponder, UIApplicationDelegate, GADFullScreenContentDelegate {
   let nc = NotificationCenter.default
   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
       GADMobileAds.sharedInstance().start(completionHandler: nil)
       return true
   }
   
   var appOpenAd: GADAppOpenAd?
   var loadTime = Date()
   
   func requestAppOpenAd() {
       let request = GADRequest()
       GADAppOpenAd.load(withAdUnitID: "ca-app-pub-3940256099942544/5662855259",
                         request: request,
                         orientation: UIInterfaceOrientation.portrait,
                         completionHandler: { (appOpenAdIn, _) in
                           self.appOpenAd = appOpenAdIn
                           self.appOpenAd?.fullScreenContentDelegate = self
                           self.loadTime = Date()
                           print("Ad is ready")
                         })
   }
   
   func tryToPresentAd() {
       if let gOpenAd = self.appOpenAd, let rwc = UIApplication.shared.windows.last!.rootViewController, wasLoadTimeLessThanNHoursAgo(thresholdN: 4) {
           gOpenAd.present(fromRootViewController: rwc)
       } else {
           self.requestAppOpenAd()
       }
   }
   
   func wasLoadTimeLessThanNHoursAgo(thresholdN: Int) -> Bool {
       let now = Date()
       let timeIntervalBetweenNowAndLoadTime = now.timeIntervalSince(self.loadTime)
       let secondsPerHour = 3600.0
       let intervalInHours = timeIntervalBetweenNowAndLoadTime / secondsPerHour
       return intervalInHours < Double(thresholdN)
   }
   
   func applicationDidBecomeActive(_ application: UIApplication) {
       self.tryToPresentAd()
   }
   
   func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
       requestAppOpenAd()
   }
   
   func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
       requestAppOpenAd()
   }
   
   func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
       print("Ad did present")
   }
}

如何在使用 SwiftUI App Cycle 而不是 AppDelegate 的 SwiftUI 项目中成功实施 AdMob 开放式广告?

【问题讨论】:

  • 你能解决这个问题吗?谢谢
  • 您好,我找到了一种轻松实现它的方法。我发表了一个答案。

标签: swift swiftui admob


【解决方案1】:

可以通过以下方式在具有 Swift UI 生命周期SwiftUI 应用 中实施 Admob Open Ad

  1. 新建一个OpenAd类:(记得导入GoogleMobileAds)
final class OpenAd: NSObject, GADFullScreenContentDelegate {
   var appOpenAd: GADAppOpenAd?
   var loadTime = Date()
   
   func requestAppOpenAd() {
       let request = GADRequest()
       GADAppOpenAd.load(withAdUnitID: "ca-app-pub-3940256099942544/5662855259",
                         request: request,
                         orientation: UIInterfaceOrientation.portrait,
                         completionHandler: { (appOpenAdIn, _) in
                           self.appOpenAd = appOpenAdIn
                           self.appOpenAd?.fullScreenContentDelegate = self
                           self.loadTime = Date()
                           print("[OPEN AD] Ad is ready")
                         })
   }
   
   func tryToPresentAd() {
       if let gOpenAd = self.appOpenAd, wasLoadTimeLessThanNHoursAgo(thresholdN: 4) {
           gOpenAd.present(fromRootViewController: (UIApplication.shared.windows.first?.rootViewController)!)
       } else {
           self.requestAppOpenAd()
       }
   }
   
   func wasLoadTimeLessThanNHoursAgo(thresholdN: Int) -> Bool {
       let now = Date()
       let timeIntervalBetweenNowAndLoadTime = now.timeIntervalSince(self.loadTime)
       let secondsPerHour = 3600.0
       let intervalInHours = timeIntervalBetweenNowAndLoadTime / secondsPerHour
       return intervalInHours < Double(thresholdN)
   }
   
   func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
       print("[OPEN AD] Failed: \(error)")
       requestAppOpenAd()
   }
   
   func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
       requestAppOpenAd()
       print("[OPEN AD] Ad dismissed")
   }
   
   func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
       print("[OPEN AD] Ad did present")
   }
}
  1. App 结构中的 OpenAd 类创建一个 ad 对象:
var ad = OpenAd()
  1. 应用激活时展示广告:
ad.tryToPresentAd()

结构 App 应该是这样的结构:

@main
struct MyApp: App {
    @Environment(\.scenePhase) private var scenePhase
    var ad = OpenAd()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { phase in
            if phase == .active {
                ad.tryToPresentAd()
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2023-02-04
    • 1970-01-01
    • 2020-02-11
    • 2021-11-10
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多