Подарите промежуточную рекламу каждый раз, когда представлен View Controller - Swift 4 - PullRequest
0 голосов
/ 26 января 2019

Я просто хочу, чтобы промежуточная реклама появлялась каждый раз, когда появляется определенный View Controller.Вот соответствующий код (не все) ...

//import ads, set delegate, and declare variable...
import UIKit
import GoogleMobileAds

class myVC: UIViewController, GADInterstitialDelegate {

var interstitial: GADInterstitial!

Подготовьте объявление и представьте его при представлении View Controller ...

override func viewDidLoad() {
    super.viewDidLoad()

    interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
    let request = GADRequest()
    interstitial.load(request)
}


override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if (interstitial.isReady) {
        interstitial.present(fromRootViewController: self)
        interstitial = createAd()
    }
}

Убедитесь, что реклама будетготов к следующему разу ...

func createAd() -> GADInterstitial {

    let inter = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")

    inter.load(GADRequest())
    return inter
}

Так почему же это не работает?Я могу показать объявление, нажав кнопку (для этого я, очевидно, немного изменил код), но я хочу, чтобы объявление просто отображалось вместе с презентацией на View Controller.Чего мне не хватает?

1 Ответ

0 голосов
/ 27 января 2019

Проблема, которую я заметил с interstitial ad, заключается в том, что он не готов при вызове viewWillAppear или viewDidAppear. Из-за этого проверка на interstitial.isReady не проходит. Метод GADInterstitialDelegate вызвал interstitialDidReceiveAd, который сообщит вам, когда добавление будет готово. Затем вам нужно построить некоторую логику для мониторинга, когда реклама готова, и если вы уже отображаете рекламу для пользователя.

import UIKit
import GoogleMobileAds

class AdViewController:UIViewController, GADInterstitialDelegate {

    var interstitial: GADInterstitial!

    private var shouldDisplayAd = true

    private var isAdReady:Bool = false {
        didSet {
            if isAdReady && shouldDisplayAd {
                displayAd()
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        print(#function)
        interstitial = GADInterstitial(adUnitID: "/6499/example/interstitial")
        interstitial.delegate = self
        let request = GADRequest()
        interstitial.load(request)
        print(#function, "shouldDisplayAd", self.shouldDisplayAd, "isAdReady", self.isAdReady)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(#function, "shouldDisplayAd", self.shouldDisplayAd, "isAdReady", self.isAdReady)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print(#function, "shouldDisplayAd", self.shouldDisplayAd, "isAdReady", self.isAdReady)
    }

    @IBAction func adButton(_ sender: UIButton) {
        print(#function, "shouldDisplayAd", self.shouldDisplayAd, "isAdReady", self.isAdReady)
        displayAd()
    }

    private func displayAd() {
        print(#function, "ad ready", interstitial.isReady)
        if (interstitial.isReady) {
            shouldDisplayAd = false
            interstitial.present(fromRootViewController: self)
        }
    }

    private func presentViewController() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let myVC = storyboard.instantiateViewController(withIdentifier: "buttonViewController")
        self.present(myVC, animated: true) { [unowned self] in
            self.shouldDisplayAd = true
            print(#function, "shouldDisplayAd", self.shouldDisplayAd, "isAdReady", self.isAdReady)
        }
    }

    func createAndLoadInterstitial() -> GADInterstitial {
        interstitial = GADInterstitial(adUnitID: "/6499/example/interstitial")
        interstitial.delegate = self
        interstitial.load(GADRequest())
        shouldDisplayAd = false
        return interstitial
    }

    /// Tells the delegate an ad request failed.
    func interstitialDidFail(toPresentScreen ad: GADInterstitial) {
        print(#function, "ad ready", interstitial.isReady)
    }

    func interstitialDidReceiveAd(_ ad: GADInterstitial) {
        print(#function, "ad ready", interstitial.isReady)
        isAdReady = true
    }

    //Tells the delegate the interstitial is to be animated off the screen.
    func interstitialWillDismissScreen(_ ad: GADInterstitial) {
        print("interstitialWillDismissScreen")
    }

    //Tells the delegate the interstitial had been animated off the screen.
    func interstitialDidDismissScreen(_ ad: GADInterstitial) {
        print("interstitialDidDismissScreen")
        presentViewController()
        interstitial = createAndLoadInterstitial()
        print(#function, "shouldDisplayAd", shouldDisplayAd, "isAdReady", isAdReady)
    }
}
...