Use the AdMob Helper for Banner Ads

To use the AdMob helper file, you first need to set up a struct to hold some static properties.

In the AdMobHelper.swift file, and after the import statements, add the following struct:

 struct​ ​AdMobHelper​ {
 static​ ​let​ bannerAdDisplayTime: ​TimeInterval​ = 30
 static​ ​let​ bannerAdID = ​"ca-app-pub-3940256099942544/2934735716"​ ​// test id
 }

The first property is the time, in seconds, each banner ad will remain visible on the screen. The second property holds the ad unit ID. Because you’re still testing and developing the game, it’s best to use the ID shown in the example. See Using Test Ad Units for more information about testing ads.

Ultimately, you need to extend the functionality of the GameViewController class to handle the ad functionality, so it makes sense to create an extension. Below the code you just added, add a new GameViewController extension, like this:

 extension​ ​GameViewController​ {
 
 }

With banner ads, you need a view to display them. To create a reusable view, you’ll set up a property to hold it. The trouble is, Swift extensions don’t support stored properties, which means you need to get a little creative.

Above the GameViewController extension you just added, add the following file-private property:

 fileprivate​ ​var​ _adBannerView = ​GADBannerView​(adSize: kGADAdSizeBanner)

Within the new GameViewController extension, add the following computed property:

 // MARK: - Properties
 var​ adBannerView: ​GADBannerView​ {
 get​ {
 return​ _adBannerView
  }
 set​(newValue) {
  _adBannerView = newValue
  }
 }

What you end up with is something like this:

 fileprivate​ ​var​ _adBannerView = ​GADBannerView​(adSize: kGADAdSizeBanner)
 
 extension​ ​GameViewController​ {
 // MARK: - Properties
 var​ adBannerView: ​GADBannerView​ {
 get​ {
 return​ _adBannerView
  }
 set​(newValue) {
  _adBannerView = newValue
  }
  }
 }

Here, you’re creating a file-private property, _adBannerView, that is only available to this file. You’re also creating a computed property with a getter and setter. This computed property returns the value of the file-private property.

You’re ready to set up the view.

Setting up the Banner Ad View

Still inside the AdMobHelper.swift file, add the following new method to the GameViewController extension:

 // Set up Banner Ads
 func​ ​setupBannerAdsWith​(id: ​String​) {
 
 // Set up the banner ads and the banner view
  adBannerView.adUnitID = id
  adBannerView.delegate = ​self
  adBannerView.rootViewController = ​self
 
 // Add the banner view to the view
 addBannerViewToView​(adBannerView)
 
 // Start serving ads
 startServingAds​(after: ​AdMobHelper​.bannerAdDisplayTime)
 }

This new method sets some properties of the GADBannerView object—in this case, the adBannerView you created earlier—and calls two additional methods, which you’ll write now (so ignore the errors).

The first method will add the ad banner view as a subview of the GameViewController.view. It’ll also set some constraint properties.

Below the setupBannerAdsWith(id:) method, add the following code:

 // Add the ad banner to the view
 func​ ​addBannerViewToView​(_ bannerView: ​GADBannerView​) {
  bannerView.translatesAutoresizingMaskIntoConstraints = ​false
  view.​addSubview​(bannerView)
 NSLayoutConstraint​.​activate​([
  bannerView.topAnchor.​constraint​(equalTo: view.topAnchor),
  bannerView.centerXAnchor.​constraint​(equalTo: view.centerXAnchor)
  ])
 }

The second method will make the call to start the request. Below the method you just added, add the following code:

 // Start serving ads using a scheduled timer
 func​ ​startServingAds​(after seconds: ​TimeInterval​) {
 // Start serving banner ads after XX seconds
 Timer​.​scheduledTimer​(timeInterval: seconds, target: ​self​,
  selector: ​#selector(​​requestAds(_:)​​)​,
  userInfo: adBannerView, repeats: ​false​)
 }

Here, you’re using a scheduled timer[62] to make the call, and you’re passing in the adBannerView as the userInfo object. You’ll read this object later in the selector method. You still need to add this method (along with its counterpart), which is why you’re seeing another error.

Below the startServingAds(after:) method, add two new methods:

 // Start serving banner ads
 @objc​ ​func​ ​requestAds​(_ timer: ​Timer​) {
 let​ bannerView = timer.userInfo ​as?​ ​GADBannerView
 let​ request = ​GADRequest​()
  bannerView?.​load​(request)
 
  timer.​invalidate​()
 }
 
 // Hide banner
 @objc​ ​func​ ​hideBanner​(_ timer: ​Timer​) {
 let​ bannerView = timer.userInfo ​as!​ ​GADBannerView
 UIView​.​animate​(withDuration: 0.5) {
  bannerView.alpha = 0.0
  }
 
  timer.​invalidate​()
 }

In a way, these methods—well, at least the first one—are at the heart of the helper file. In requestAds(_:), you use the object stored in timer.userInfo, which is the adBannerView, to request an ad using the load(_:) method of the GADRequest object. To put it simply: this is what loads the first (or next) ad.

The second method, hideBanner(_:), is the method you’ll use to hide the banner view gracefully.

Everything is now in place to start serving banner ads.

Serving and Handling Banner Ads

The Google Mobile Ads SDK uses the delegate pattern to keep track of important events related to serving and handling ads. The AdMob helper file you added in Add the AdMob Helper File has the delegate method stubs you’ll use to handle ads using a GameViewController extension.

In the AdMobHelper.swift file, locate the adViewDidReceiveAd(_:) method. This is the method that gets called when the request returns an ad, and it’s within this method where you animate the banner view to show the ad.

Add the following code at the end of the adViewDidReceiveAd(_:) method:

 adBannerView = bannerView
 UIView​.​animate​(withDuration: 0.5,
  animations: {[​weak​ ​self​] ​in​ ​self​?.adBannerView.alpha = 1.0})
 
 // Auto-hide banner
 Timer​.​scheduledTimer​(timeInterval: ​AdMobHelper​.bannerAdDisplayTime,
  target: ​self​,
  selector: ​#selector(​​hideBanner(_:)​​)​,
  userInfo: bannerView, repeats: ​false​)

This small update sets the adBannerView property and animates the banner view so that it slowly fades in once the ad is ready. It then fires off a scheduled timer, calling the hideBanner(_:) method.

Hang in there, you’re almost ready to test your ads.

Open the GameViewController.swift file, and in the viewDidLoad() method, below the line that reads view.showsNodeCount = false, add this code:

 // Set up Google AdMob
 setupBannerAdsWith​(id: ​AdMobHelper​.bannerAdID)

Okay, are you ready for the big reveal? Build and run the project. After waiting for about a minute, you’ll see your first Google test ad:

images/UsingAdsToIncreaseRevenue/ads-build-01.png

Now that you know how to work with banner ads, you’re ready to move on to rewarded ads. But first, you need to set up the Continue Game feature so that you’ll have a reward worthy of offering.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset