【发布时间】: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 开放式广告?
【问题讨论】:
-
你能解决这个问题吗?谢谢
-
您好,我找到了一种轻松实现它的方法。我发表了一个答案。