Search code examples
swiftswiftuiinterstitialgoogle-mobile-adsgadinterstitial

SwiftUI: Admob Interstitial Ad is not being presented on rootViewController


CODED IN SWIFTUI

I have implemented a settings page within my SwiftUI app that is presented upon clicking the button within the view. This view is wrapped within a sheet. You can see the code below:

TabsBar(showOptionsTab: $showOptionsTab)
    .sheet(isPresented: $showOptionsTab)
    {
        OptionsTab(showOptionsTab: self.$showOptionsTab)
    }

I have implemented an interstitial within this "OptionsTab" that is created when the options tab is loaded within the .onAppear() call and presented when the back button is selected. You can the code from the OptionsTab below:

@State private var interstitial : GADInterstitial!

VStack
{
    ... other code

    Button(action:
    {
        if ( self.interstitial.isReady)
        { 
            let root = UIApplication.shared.windows.first?.rootViewController
            self.interstitial.present(fromRootViewController: root!)               
        }

        self.showOptionsTab.toggle()
    })
    {
        Image(systemName: "xmark")
            .font(.largeTitle)
    }
}
.onAppear
{
    self.interstitial = GADInterstitial(adUnitID: "addID")
    let req = GADRequest()
    self.interstitial.load(req) 
}

I have additional code within the button that logs the status of the interstitial, and it shows it as being READY, and the present code is being hit... but it never presents itself.

I have implemented this exact code in the ContentView, and the interstitial loads perfectly fine. Something about this code being within the sheet is causing the interstitial not to present.

Is the rootViewController the incorrect view to load the interstitial on when in a view that is presented from a sheet? Otherwise, what else am I doing wrong?

Thanks for the help in advance!


Solution

  • Try this

    TabsBar(showOptionsTab: $showOptionsTab)
        .sheet(isPresented: $showOptionsTab)
        {
            OptionsTab(showOptionsTab: self.$showOptionsTab)
                .OnDisapear 
                {    
                    if ( self.interstitial.isReady)
                    { 
                        let root = UIApplication.shared.windows.first?.rootViewController
                        self.interstitial.present(fromRootViewController: root!)               
                    }
                } 
            }
        }
    

    And then add the state interstitial variable within this view, and onAppear of the ContextView, create the interstitial there.