I want to design a swiftui view MainView() where an interstitial ad will be presented without reloading MainView().
My strategy is:
- Load ad from GADInterstitialAd,
- Present the ad on a UIViewController(). Then make UIViewControllerRepresentable to be presentable in swiftui.
- Present it to the MainView() using fullScreenCover(isPresented: , content: ) modifier.
But every time while the ad presented, the MainView() goes to .onDisappear state, and after closing the ad, it goes to .onAppear state. For that reason the MainView() is fully reloaded. I want to stop this reloading issue. How should I actually present the ad in my view?
Update: Here I have added AdView for more clarification.
struct nterstitialAdView: UIViewControllerRepresentable {
var interstitialAd: GADInterstitialAd?
var callback: () -> Void
func makeUIViewController(context: Context) -> UIViewController {
let view = UIViewController()
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1)) {
self.showAd(from: view, callback: callback)
}
return view
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
}
func showAd(from root: UIViewController, callback: () -> Void) {
if let ad = interstitialAd {
ad.present(fromRootViewController: root)
callback()
print(":: Ad Presented")
} else {
print(":: Ad not ready")
callback()
}
}
}
2
Answers
Rather than present using
fullScreenCover
, how about displaying the ViewController in aZStack
, for example:It should be pretty straightforward to animate the AdView in, if that’s what’s required.
You can track in a
Bool
whether your page has already loaded and not reload it if it did.Other than that The iOS is made to execute
OnAppear
in that case, that happens both inUIKit
andSwiftUI
, so even callingUIKit
in help won’t work.