我正在使用SpriteKit制作iOS游戏,并且刚刚实施了adMob(链接到Firebase)。但是,按照Google提供的步骤并将代码添加到ViewController后,它会在所有场景中显示广告,例如主菜单场景,游戏场景和场景游戏。我希望横幅广告只显示在主菜单和游戏场景上。
以下是我在GameViewController中的代码:
import GoogleMobileAds
var bannerView: GADBannerView!
var admobBanner = UIView()
class GameViewController: UIViewController, GADBannerViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
//Advertisments
// In this case, we instantiate the banner with desired ad size.
bannerView = GADBannerView(adSize: kGADAdSizeBanner)
addBannerViewToView(bannerView)
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.delegate = self
bannerView.load(GADRequest())
admobBanner = bannerView
//
if let view = self.view as! SKView? {
// Load the SKScene from 'MainMenuScene.sks'
if let scene = MainMenuScene(fileNamed: "MainMenuScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .resizeFill //change back to aspectFill if experiencing problems
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
//Advertisments
func addBannerViewToView(_ bannerView: GADBannerView) {
bannerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bannerView)
view.addConstraints([NSLayoutConstraint(item: bannerView, attribute: .bottom, relatedBy: .equal, toItem: bottomLayoutGuide, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: bannerView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)])
}
稍后,要隐藏GameScene上的广告,我将此代码放在GameScene的DidMoveToView中:
admobBanner.removeFromSuperview()
这可以隐藏游戏场景中的横幅广告,但不会在其他场景中重新启用。我如何"重新启用"它在MainMenu和GameOver场景中?我尝试这样做以重新启用MainMenu和GameOver场景中的广告,但它不起作用(错误和警告已显示为注释):
func showBanner(){
if admobBanner == nil { //WARNING: Comparing non-optional value of type 'UIView' to nil always returns false
bannerView = GADBannerView(adSize: kGADAdSizeBanner)
addBannerViewToView(bannerView) //ERROR: Use of unresolved identifier 'addBannerViewToView'
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.delegate = self //ERROR: Cannot assign value of type 'MainMenuScene' to type 'UIViewController?'
bannerView.load(GADRequest())
admobBanner = bannerView
}
}
所以,问题是,如何在某些场景中展示横幅广告并将其隐藏在其他场景中?任何帮助深表感谢! :)
答案 0 :(得分:1)
处理GameViewController.swift
文件中的所有横幅内容。在那里,为bannerView
变量分配标记值。然后,当场景加载时,使用标记ID加载bannerView
,然后将其.isHidden
属性设置为true
。
GameViewController.swift
bannerView.tag = 100
Game.swift
// hide banner
let bannerView = self.view?.viewWithTag(100) as! GADBannerView?
bannerView?.isHidden = true
您也可以在其他场景上执行此操作,只需确保为您执行此操作的每个场景导入Google SDK。