【问题标题】:Implementing AdMob Interstitial Ads in SwiftUI (5) and Xcode (12.4)在 SwiftUI (5) 和 Xcode (12.4) 中实现 AdMob 插页式广告
【发布时间】:2021-09-11 01:31:10
【问题描述】:

我正在努力在我的应用中实施插页式广告,但对 Admob 提供的文档和新的 SwiftUI 应用结构感到有些困惑。

这是 app.swift 文件,显示我已实现 GoogleMobileAds 并在 didFinishLaunchingWithOptions 方法中启动它。

import SwiftUI
import GoogleMobileAds

@main
struct adamsCalcApp: App {
    var calculator = Calculator()
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView().environmentObject(calculator)
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // Setup google admob instance
        GADMobileAds.sharedInstance().start(completionHandler: nil)
        return true
    }

}

在我的 ContentView.swift 文件中,我创建了间隙变量,如...

 @State var interstitial: GADInterstitialAd?

然后在视图的主堆栈上,我调用 onAppear(perform: ) 来加载广告,但是我一直收到此错误。

.onAppear(perform: {
            let request = GADRequest()
                    GADInterstitialAd.load(withAdUnitID:"ca-app-pub-3940256099942544/4411468910",
                                                request: request,
                                      completionHandler: { [self] ad, error in
                                        if let error = error {
                                          return
                                        }
                                        interstitial = ad
                                        interstitial?.fullScreenContentDelegate = self
                                      }
                    )

        })

“无法将类型 'ContentView' 的值分配给类型 'GADFullScreenContentDelegate?'"

在尝试了几种不同的解决方法并尝试查找与我类似的设置后,我感觉有点不知所措,AdMob 文档仍然显示如何使用类 ViewControllers 实现,我想弄清楚如何做到这一点是 SwiftUI .

【问题讨论】:

  • 你搜索过“SwiftUI interstitial”吗?有许多结果可能对您有用。
  • 在浏览了 SwiftUI Interstitial 之后,我发现了对我有用的差异,我将在下面发布答案。
  • 请看一下 SwiftUI 中的广告要点 - gist.github.com/dhanrajdc7/6442ff07fc27a15b4f062f70b3be2684
  • 在 SwiftUI 中的 Ads 要点略有弃用,GADInterstitialDelegate 和 GADInterstitial 不再在范围内。

标签: xcode swiftui admob


【解决方案1】:

为了在最新的 SwiftUI 版本中使用 Admob 文档,您需要更改此行...

        .onAppear(perform: {
                    let request = GADRequest()
                            GADInterstitialAd.load(withAdUnitID:"ca-app-pub-3940256099942544/4411468910",
                                                        request: request,
                                              completionHandler: { [self] ad, error in
                                                if let error = error {
                                                  return
                                                }
                                     // Change these two lines of code
                                     interstitial = ad
                                                
                                     interstitial?.fullScreenContentDelegate = self
                                     // To...
                                     interstitial = ad
                                     let root = UIApplication.shared.windows.first?.rootViewController                                        
                      self.interstitial!.present(fromRootViewController: root!)
                                              }
                            )
        
                })

【讨论】:

    【解决方案2】:
    import SwiftUI
    import GoogleMobileAds
    import AppTrackingTransparency
    import AdSupport
    
    class AdsManager: NSObject, ObservableObject {
        
        private struct AdMobConstant {
            static let interstitial1ID = "..."
        }
        
        final class Interstitial: NSObject, GADFullScreenContentDelegate, ObservableObject {
    
            private var interstitial: GADInterstitialAd?
            
            override init() {
                super.init()
                requestInterstitialAds()
            }
    
            func requestInterstitialAds() {
                let request = GADRequest()
                request.scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
                ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                    GADInterstitialAd.load(withAdUnitID: AdMobConstant.interstitial1ID, 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
                    })
                })
            }
            func showAd() {
                let root = UIApplication.shared.windows.last?.rootViewController
                if let fullScreenAds = interstitial {
                    fullScreenAds.present(fromRootViewController: root!)
                } else {
                    print("not ready")
                }
            }
            
        }
        
        
    }
    
    
    class AdsViewModel: ObservableObject {
        static let shared = AdsViewModel()
        @Published var interstitial = AdsManager.Interstitial()
        @Published var showInterstitial = false {
            didSet {
                if showInterstitial {
                    interstitial.showAd()
                    showInterstitial = false
                } else {
                    interstitial.requestInterstitialAds()
                }
            }
        }
    }
    
    @main
    struct YourApp: App {
        let adsVM = AdsViewModel.shared
        init() {
            GADMobileAds.sharedInstance().start(completionHandler: nil)
        }
    
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .environmentObject(adsVM)
        }
    }
    

    在应用程序的任意位置切换 AdsViewModel 中的 showInterstitial 参数,就会显示广告。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      相关资源
      最近更新 更多