I am trying to show google ad banner in a List view in alternative cells. such that whenever ads get successfully loaded the cell should automatically expand and show the ad in the list view and whereas the ads gets failed to load the list view cell should collapse and shouldn’t show the ads
The below code snippet is for AdBanner in Swift UI
struct ContentView: View {
let bannerId = "ca-app-pub-3940256099942544/2934735716"
var body: some View {
ZStack {
VStack(alignment: .center, spacing: 0) {
navBar()
.background(Color.blue)
List(0..<10) { _ in
HStack {
FixedSpacer()
AdBannerView(bannerID: bannerId, adWidth: 320, adHeight: 50)
FixedSpacer()
}
Text("Hello world!")
}
.listStyle(.plain)
FixedSpacer()
}
}
}
import UIKit
import SwiftUI
import GoogleMobileAds
struct AdBannerView: UIViewControllerRepresentable {
var bannerID: String
var adWidth: CGFloat
var adHeight: CGFloat
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeUIViewController(context: Context) -> UIViewController {
print("makeUIViewController called")
let bannerView = GADBannerView(frame: CGRect(x: 0, y: 0, width: adWidth, height: adHeight))
let viewController = UIViewController()
bannerView.adUnitID = bannerID
bannerView.rootViewController = viewController
viewController.view.addSubview(bannerView)
bannerView.load(GADRequest())
bannerView.delegate = context.coordinator
return viewController
}
@available(iOS 16.0, *)
func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: UIViewController, context: Context) -> CGSize? {
CGSize(width: adWidth, height: adHeight)
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
print("updateUIViewController called")
}
class Coordinator : NSObject, GADBannerViewDelegate {
var parent : AdBannerView
init(_ parent : AdBannerView) { self.parent = parent }
public func bannerViewDidReceiveAd(_ bannerView: GADBannerView) {
print("Ads received successfully")
}
public func bannerView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: Error) {
print("Ad loads to fail: \(error.localizedDescription)")
}
}
}
In case if the banner ad gets failed the white space is appearing in the list view cells.
But i am unable to find the solution for this problem. could anyone can help on this issue?
attached the screenshot for the reference Screenshot of the app