Показ межстраничного объявления с помощью кнопки, которая также переключает другое представление с листа - PullRequest
0 голосов
/ 09 июля 2020

, так что у меня есть это тестовое приложение, состоящее из двух представлений. В родительском представлении есть кнопка, которая переключает второе представление (нижний модальный лист). Моя цель - показывать межстраничную рекламу AdMob при нажатии кнопки. Но все же есть второй взгляд, когда объявление отклонено. В настоящее время объявление отображается, но при закрытии объявления оно возвращается к родительскому представлению без переключения второго представления. Возможно ли наложение представления объявления поверх второго представления, чтобы при отклонении объявления пользователь уже находился во втором представлении?

import GoogleMobileAds
import SwiftUI
import UIKit

struct ContentView: View {
    @State var showingTest = false
    @State var showingDisclaimer = false
    
    //Ad
    var interstitial: Interstitial
    
    init() {
        self.interstitial = Interstitial()
    }
    
    var body: some View {
        // QuestionsView()
        // NavigationView {
        VStack {
            
            Button(action: {
                self.showingTest.toggle()
                self.interstitial.showAd()
                }) {
                Text("take the test!")
                    .fontWeight(.bold)
                    .foregroundColor(Color.white)
            }
            .frame(minWidth: 0, maxWidth: .infinity)
            .padding()
            .foregroundColor(.gray)
            .background(Color("raisinblack"))
            .cornerRadius(10)
            .font(.title)
            .sheet(isPresented: $showingTest) {
                QuestionsView()
            }.padding()
            .shadow(radius: 5)
        }
        .padding()
        .frame(minWidth: 0, maxWidth: .infinity)
        .navigationBarTitle("rice purity test.")
    }
}

Я новичок в swiftUI, поэтому я не уверен, как go об этой работе. Я понимаю, что проблема возникает из-за того, что я пытаюсь одновременно представить два представления.

Ошибка:

Warning: Attempt to present <_TtGC7SwiftUIP10$1c95b7a6c22SheetHostingControllerVS_7AnyView_: 0x1056344f0> on <_TtGC7SwiftUI19UIHostingControllerV14RicePurityTest11ContentView_: 0x10560f280> whose view is not in the window hierarchy!

Межстраничный класс


final class Interstitial: NSObject, GADInterstitialDelegate {
    var interstitial: GADInterstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
    
    override init() {
        super.init()
        self.LoadInterstitial()
    }
    
    func LoadInterstitial() {
        let req = GADRequest()
        self.interstitial.load(req)
        self.interstitial.delegate = self
    }
    
    func showAd() {
        if self.interstitial.isReady {
            let root = UIApplication.shared.windows.first?.rootViewController
            
            self.interstitial.present(fromRootViewController: root!)
        } else {
            print("Not Ready")
        }
    }
    
    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        self.interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
        self.LoadInterstitial()
        
    }
    
    /// Tells the delegate an ad request succeeded.
    func interstitialDidReceiveAd(_ ad: GADInterstitial) {
        print("interstitialDidReceiveAd")
    }
    
    /// Tells the delegate an ad request failed.
    func interstitial(_ ad: GADInterstitial, didFailToReceiveAdWithError error: GADRequestError) {
        print("interstitial:didFailToReceiveAdWithError: \(error.localizedDescription)")
    }
    
    /// Tells the delegate that an interstitial will be presented.
    func interstitialWillPresentScreen(_ ad: GADInterstitial) {
        print("interstitialWillPresentScreen")
    }
    
    /// Tells the delegate the interstitial is to be animated off the screen.
    func interstitialWillDismissScreen(_ ad: GADInterstitial) {
        print("interstitialWillDismissScreen")
        //showingTest.toggle()
    }
    
    /// Tells the delegate that a user click will open another app
    /// (such as the App Store), backgrounding the current app.
    func interstitialWillLeaveApplication(_ ad: GADInterstitial) {
        print("interstitialWillLeaveApplication")
    }
}

1 Ответ

0 голосов
/ 10 июля 2020
func showAd() {
    if self.interstitial.isReady {
        let root = UIApplication.shared.windows.last?.rootViewController
        // you can also use: UIApplication.shared.keyWindow.rootViewController
           self.interstitial.present(fromRootViewController: root!)
    } else {
        print("Not Ready")
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...