gpt4 book ai didi

swift - 确定何时在 SwiftUI 中加载 Google 横幅广告

转载 作者:行者123 更新时间:2023-12-04 15:32:10 28 4
gpt4 key购买 nike

这是用 Swift 编码的

我已成功将 Google 横幅广告添加到我的应用程序的设置页面。我已经在下面实现了它:

import Foundation
import SwiftUI
import GoogleMobileAds

struct AdView : UIViewRepresentable
{
@Binding var AdLoaded : Bool

func makeUIView(context: UIViewRepresentableContext<AdView>) -> GADBannerView
{
let banner = GADBannerView(adSize: kGADAdSizeBanner)
banner.adUnitID = "realAdId"
banner.rootViewController = UIApplication.shared.windows.first?.rootViewController
banner.load(GADRequest())
return banner
}

func updateUIView(_ uiView: GADBannerView, context: UIViewRepresentableContext<AdView>){}

public func adViewDidReceiveAd(_ bannerView: GADBannerView)
{
AdLoaded = true
if (DEBUG_ADS ) { print("Banner Ad Did Find Ad!") }
}

public func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError)
{
AdLoaded = false
if (DEBUG_ADS ) { print(error) }
}
}

我知道,由于我在此结构中没有 GADBannerViewDelegate,因此我无权访问我已实现的功能(adViewDidReceiveAdadView...didFailToReceiveAdWithError)。他们永远不会按原样被调用。

我已经搞砸了很多,但我找不到合适的方法来实现这些委托(delegate)功能。

我的预期功能是在我的设置页面中实现此 AdView:

if ( someBindingVariable??? )
{
AdView(AdLoaded: self.$AdLoaded)
}

它目前的工作方式是在加载之前为 AdView 留出空间。加载广告后,空间就会被广告填满。我希望只有在加载广告后才添加空间。

感谢您的帮助,如果我对某些事情不清楚,请告诉我!

最佳答案

根据@Asperi 的评论,我用我的 AdView 实现了一个 Coordinator,它起作用了!

见下文:

import Foundation
import SwiftUI
import GoogleMobileAds

struct AdView : UIViewRepresentable
{
@Binding public var AdLoaded : Bool
public var bannerId : String

func makeCoordinator() -> Coordinator
{
Coordinator(self)
}

func makeUIView(context: UIViewRepresentableContext<AdView>) -> GADBannerView
{
let banner = GADBannerView(adSize: kGADAdSizeBanner)
banner.adUnitID = bannerId
banner.rootViewController = UIApplication.shared.windows.first?.rootViewController
banner.load(GADRequest())
banner.delegate = context.coordinator
return banner
}

func updateUIView(_ uiView: GADBannerView, context: UIViewRepresentableContext<AdView>){}

class Coordinator: NSObject, GADBannerViewDelegate
{
var parent: AdView

init(_ parent: AdView)
{
self.parent = parent
}

func adViewDidReceiveAd(_ bannerView: GADBannerView)
{
parent.AdLoaded = true
if ( DEBUG_ADS ) { print("Ad View Did Receive Ad For ID: \(parent.bannerId)")}
}

func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError)
{
parent.AdLoaded = false
if ( DEBUG_ADS ) { print("Ad View Failed To Receive Ad For ID: \(parent.bannerId)")}
}
}
}

关于swift - 确定何时在 SwiftUI 中加载 Google 横幅广告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61047855/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com