добавить рекламный баннер в uiViewController в Swift3

Я хочу добавить и рекламный баннер, я использовал google framework

pod 'Google-Mobile-Ads-SDK'

в моем подфайле

Я добавил представление в свой uiViewController> GoogleBannerView

это мой код

импортировать GoogleMobileAds

в viewdidLoad:

    GoogleBannerView.adUnitID = "ca-app-pub-5462393278951241/1172515484"
    GoogleBannerView.delegate = self
    GoogleBannerView.rootViewController = self
    GoogleBannerView.load(GADRequest())

Но он ничего не отображает в представлении и выдает мне сообщение в консоли:

Чтобы получить тестовые объявления на этом устройстве, вызовите: request.testDevices = @[ kGADSimulatorID ];

Любая помощь приветствуется! Спасибо..


person ema so    schedule 17.01.2018    source источник
comment
Зарегистрируйтесь в iPhone один раз, а не в симуляторе @ema, так что   -  person Datt Patel    schedule 17.01.2018


Ответы (1)


Я показываю объявление в нижнем колонтитуле (320 x 50), которое будет появляться снизу, если оно есть, и уменьшаться, если оно перестанет показываться. Это тяжелая реализация, и ее можно упростить, если вы не хотите скрывать/показывать пространство.

Мой UIViewController имеет жестко закодированное представление с ограничениями (ширина 320, высота 50, центрировано по горизонтали, закреплено в нижней части безопасной области. Я связываю следующее:

  • Просмотр рекламы в баннере
  • Ограничение высоты просмотра рекламы для bannerViewHeightConstraint

Обратите внимание, что в примере кода я использую ваш adUnitID. Наш идентификатор выглядит иначе, поскольку мы используем DFP.

import GoogleMobileAds

class SomeClass: UIViewController
{
    @IBOutlet weak var bannerView: DFPBannerView!
    @IBOutlet weak var bannerViewHeightConstraint: NSLayoutConstraint!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        bannerView.delegate = self
        bannerView.adUnitID = "ca-app-pub-5462393278951241/1172515484"
        bannerView.rootViewController = self
        bannerView.validAdSizes = [ NSValueFromGADAdSize(kGADAdSizeBanner) ]
        bannerView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        bannerView.frame.origin.y += bannerView.frame.size.height
        bannerView.isHidden = true

        let request = GADRequest()
    //***** NOTE : per Google Documentation (https://developers.google.com/mobile-ads-sdk/docs/dfp/ios/test-ads)
    //        "iOS simulators are automatically configured as test devices."
//      request.testDevices = [ kGADSimulatorID ] //***** This was requried in previous versions, now on automatically done, don't think you can disable it.
        bannerView.load(request)
    }
}

extension SomeClass : GADBannerViewDelegate
{
    /// Tells the delegate an ad request loaded an ad.
    func adViewDidReceiveAd(_ bannerView: GADBannerView) {
        print("*** adViewDidReceiveAd for 'Banner' at \(Date())")
        if bannerView == self.bannerView
        {
            if bannerView.isHidden
            {
                bannerView.frame.origin.y += bannerView.frame.size.height
                bannerViewHeightConstraint.constant = 0
                bannerView.isHidden = false

                UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseIn, animations: {
                    bannerView.frame.origin.y -= bannerView.frame.size.height
                    self.bannerViewHeightConstraint.constant = 50
                }, completion: nil )
            }
        }
    }

    /// Tells the delegate an ad request failed.
    func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
        print("*** adView:didFailToReceiveAdWithError: \(error.localizedDescription) for 'Banner'")
        if bannerView == self.bannerView
        {
            print("Hidden: \(bannerView.isHidden)")
            if !bannerView.isHidden
            {
                UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseIn, animations: {
                    bannerView.frame.origin.y += bannerView.frame.size.height
                    self.bannerViewHeightConstraint.constant = 0
                }, completion: {finished in
                    if finished
                    {
                        bannerView.isHidden = true
                    }
                })
            }
        }
    }

    /// Tells the delegate that a full screen view will be presented in response
    /// to the user clicking on an ad.
    func adViewWillPresentScreen(_ bannerView: GADBannerView) {
        print("*** adViewWillPresentScreen for 'Banner'")
    }

    /// Tells the delegate that the full screen view will be dismissed.
    func adViewWillDismissScreen(_ bannerView: GADBannerView) {
        print("*** adViewWillDismissScreen for 'Banner'")
    }

    /// Tells the delegate that the full screen view has been dismissed.
    func adViewDidDismissScreen(_ bannerView: GADBannerView) {
        print("*** adViewDidDismissScreen for 'Banner'")
    }

    /// Tells the delegate that a user click will open another app (such as
    /// the App Store), backgrounding the current app.
    func adViewWillLeaveApplication(_ bannerView: GADBannerView) {
        print("*** adViewWillLeaveApplication for 'Banner'")
    }
}
person Random Code Monkey    schedule 17.01.2018