向SwiftUI网格添加广告的最佳方式是什么?

向SwiftUI网格添加广告的最佳方式是什么?,swiftui,admob,google-ads-api,Swiftui,Admob,Google Ads Api,您好,我想在swiftUI网格中添加广告。网格包含我从firebase后端获得的图片,在每两张图片之后,我都希望有一个广告 我对SwiftUi和使用广告都很陌生,所以我不确定我的代码有多正确,但以下是我到目前为止得到的 // Code for the pictures Grid struct PicturesGrid: View { private let data: [Item] var body: some View { let gridItems = [GridItem(.fix

您好,我想在swiftUI网格中添加广告。网格包含我从firebase后端获得的图片,在每两张图片之后,我都希望有一个广告

我对SwiftUi和使用广告都很陌生,所以我不确定我的代码有多正确,但以下是我到目前为止得到的

// Code for the pictures Grid
struct PicturesGrid: View {
private let data: [Item]

var body: some View {
    let gridItems = [GridItem(.fixed(UIScreen.screenWidth / 2),
                              alignment: .leading),
                     GridItem(.fixed(UIScreen.screenWidth / 2),
                              alignment: .leading)]
    
    return ScrollView(showsIndicators: false) {
        LazyVGrid(columns: gridItems) {
            ForEach(0..<self.data.count, id: \.self) { index in
                
                // Using this workaround for the ad to be on the whole width of the screen
                // Also, after every six images I am adding and ad
                if index != 0, index % 6 == 0 {
                    AdView()
                        .frame(width: UIScreen.screenWidth, height: 280)
                        .padding(.top, 20)
                    Spacer()
                    
                    item
                        .frame(width: UIScreen.screenWidth / 2)
                } else {
                    item
                        .frame(width: UIScreen.screenWidth / 2)
                    
                }
            }
        }
    }
}

// this is for the picture
var item: some View {
    NavigationLink(destination: DetailView(viewModel: DetailViewModel(item: itemAtIndexPath))) {
        Cell(viewModel: CellViewModel(item: itemAtIndexPath))
    }
    .buttonStyle(PlainButtonStyle())
}
}
我想说的是,这目前正在发挥作用,但我想解决的问题和我不知道如何解决的问题是:

  • 加载图片的网格,但当我滚动浏览广告时,需要几秒钟才能加载和显示广告。我怎样才能至少在它加载时隐藏它或使它更快
  • 如果我在一个广告上滚动,广告就会加载,如果我继续滚动,当我向后滚动时,广告就不再加载了,我必须等待它再次加载。我怎样才能解决这个问题?或者这种情况下的最佳实践是什么
  • 我应该使用多线程吗?在显示之前加载它们?如果是,那么我应该如何做
  • 我在这里做的看起来有点正确吗?求你了,我需要帮助

  • 在SwiftUI网格中显示广告的最佳方式是在应用程序中实现本地广告,以提供个性化的广告体验

    // Code for the ad that I am currently using
    struct AdView: UIViewControllerRepresentable {
    
    func makeUIViewController(context: Context) -> UIViewController {
        let adController = AdViewController(self)
        
        return adController
    }
    
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
    }
    
    class AdViewController: UIViewController {
    private var adView: AdView
    
    /// The height constraint applied to the ad view, where necessary.
    var heightConstraint: NSLayoutConstraint?
    
    /// The ad loader. You must keep a strong reference to the GADAdLoader during the ad loading
    /// process.
    var adLoader: GADAdLoader!
    
    /// The native ad view that is being presented.
    var nativeAdView: GADUnifiedNativeAdView!
    
    /// The ad unit ID.
    let adUnitID = "ca-app-pub-3940256099942544/3986624511"
    
    init(_ adView: AdView) {
        self.adView = adView
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var nibView: Any?
        nibView = Bundle.main.loadNibNamed("ListAdView", owner: nil, options: nil)?.first
        
        guard let nativeAdView = nibView as? GADUnifiedNativeAdView else {
            return
        }
        setAdView(nativeAdView)
        
        adLoader = GADAdLoader(adUnitID: adUnitID, rootViewController: self,
                               adTypes: [.unifiedNative], options: nil)
        
        
        
        adLoader.delegate = self
        DispatchQueue.global(qos: .background).async {
            self.adLoader.load(GADRequest())
        }
    }
    
    func setAdView(_ adView: GADUnifiedNativeAdView) {
        // Remove the previous ad view.
        DispatchQueue.main.async { [weak self] in
            guard let weakSelf = self else {
                return
            }
            weakSelf.nativeAdView = adView
            weakSelf.view.addSubview(weakSelf.nativeAdView)
            weakSelf.nativeAdView.translatesAutoresizingMaskIntoConstraints = false
            
            // Layout constraints for positioning the native ad view to stretch the entire width and height
            let viewDictionary = ["_nativeAdView": weakSelf.nativeAdView!]
            weakSelf.view.addConstraints(
                NSLayoutConstraint.constraints(
                    withVisualFormat: "H:|[_nativeAdView]|",
                    options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary)
            )
            weakSelf.view.addConstraints(
                NSLayoutConstraint.constraints(
                    withVisualFormat: "V:|[_nativeAdView]|",
                    options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: viewDictionary)
            )
        }
    }
    }
    
    extension AdViewController: GADUnifiedNativeAdLoaderDelegate {
        func adLoader(_ adLoader: GADAdLoader, didFailToReceiveAdWithError error: 
    
    GADRequestError) {
        
        print("didFailToReceiveAdWithError: \(error)")
    }
    
    func adLoader(_ adLoader: GADAdLoader, didReceive nativeAd: GADUnifiedNativeAd) {
        
        print("Received unified native ad: \(nativeAd)")
        // Deactivate the height constraint that was set when the previous video ad loaded.
        heightConstraint?.isActive = false
        
        // Populate the native ad view with the native ad assets.
        // The headline and mediaContent are guaranteed to be present in every native ad.
        (nativeAdView.headlineView as? UILabel)?.text = nativeAd.headline
        nativeAdView.mediaView?.mediaContent = nativeAd.mediaContent
        
        // This app uses a fixed width for the GADMediaView and changes its height to match the aspect
        // ratio of the media it displays.
        if let mediaView = nativeAdView.mediaView, nativeAd.mediaContent.aspectRatio > 0 {
            heightConstraint = NSLayoutConstraint(
                item: mediaView,
                attribute: .height,
                relatedBy: .equal,
                toItem: mediaView,
                attribute: .width,
                multiplier: CGFloat(1 / nativeAd.mediaContent.aspectRatio),
                constant: 0)
            heightConstraint?.isActive = true
        }
        
        // This asset is not guaranteed to be present. Check that it is before
        // showing or hiding it.
        (nativeAdView.advertiserView as? UILabel)?.text = nativeAd.advertiser
        nativeAdView.advertiserView?.isHidden = nativeAd.advertiser == nil
        
        // In order for the SDK to process touch events properly, user interaction should be disabled.
        nativeAdView.callToActionView?.isUserInteractionEnabled = false
        
        // Associate the native ad view with the native ad object. This is
        // required to make the ad clickable.
        // Note: this should always be done after populating the ad views.
        nativeAdView.nativeAd = nativeAd
    }
    }