Rewarded (or "reward-based") video ads are full screen video ads that users have the option of watching in full in exchange for in-app rewards.

This codelab will walk you through integrating rewarded video ads into an existing iOS mobile app, including the design considerations, as well as implementation details, to follow the best practices for rewarded video ads.

What you will build

In this codelab, you're going to integrate rewarded video ads into the sample application called "Impossible Game".

What you'll learn

What you'll need

For this codelab, you will start with the Impossible Game, the game that's impossible to win. A timer begins counting down at the beginning of each round and the game is over when the timer reaches zero. Once the game is over, the user is awarded a coin for playing.

Download the Code

Follow the steps listed below to download all the code for this codelab:
Click the following link to download all the code for this codelab:

  1. Download the source code from this link.
  2. Unpack the downloaded zip file.

This will unpack a root folder (admob-rewarded-video-master), which contains a directory specific to either Android or iOS. For this codelab you'll navigate to the iOS directory. The iOS directory contains the start state for this codelab, located in the work directory. The end state for this codelab is located in the final directory.

You'll do all of your coding in this codelab in the work directory. If at any time you're having trouble, you can refer to the project in the final directory.

AdMob is part of the Firebase mobile services platform, which uses a file called GoogleService-Info.plist to store configuration information about your app.

The best way to get the file is to log in to the Firebase console and register an app. For this codelab, a sample Info.plist file has been included in the project.

Use Cocoapods to get the SDKs

The easiest way to include the Firebase and Mobile Ads SDKs is using CocoaPods, which is used in this codelab. In the same directory as the RewardedVideoExample.xcodeproj file, there is already a file named Podfile that includes the following:

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '7.0'

target 'RewardedVideoExample' do
  use_frameworks!
  pod 'Firebase'
  pod 'Firebase/AdMob'
end

Run pod update

In the terminal, navigate to the same directory as the Podfile described above. Then run:

pod update

This command ensures you get the latest iOS SDK into your app and that all the APIs are there. Once the installation finishes, close the Xcode project.

Open xcworkspace

In the terminal, navigate to the same directory as the Podfile described above. Then run:

open RewardedVideoExample.xcworkspace

The Xcode project that opens should include a Pods project with new dependencies for Firebase and AdMob.

Include Info.plist file

The last step in adding the FIrebase SDK to your project is downloading a GoogleService-Info.plist file from Firebase console and including it in your app. For convenience, a sample GoogleService-Info.plist file has already been included in the project.

Before loading ads, your app will need to initialize the Firebase and Mobile Ads SDKs

Initialize Firebase

Add the call to configure:, shown below, to the application:didFinishLaunchingWithOptions:method of AppDelegate.swift to perform Firebase initialization. It's important to note you must include the import Firebase statement before calling any Firebase methods.

import Firebase
Import UIKit
...

func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

  // Initialize the Firebase SDK.
  FIRApp.configure()
  return true
}

Initialize Google Mobile Ads

Add the call to configure:withApplicationID: with your AdMob App ID to the application:didFinishLaunchingWithOptions:method of AppDelegate.swift to perform Google Mobile Ads initialization. You can find your app's App ID in the AdMob UI. For this codelab, we will use the test app ID value of ca-app-pub-3940256099942544~1458002511.

import Firebase

...

func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  FIRApp.configure()

  // Initialize the Google Mobile Ads SDK.
  GADMobileAds.configure(withApplicationID: "ca-app-pub-3940256099942544~1458002511")

  return true
}

Before going any further, a GADRewardBasedVideoAd object is required. The singleton GADRewardBasedVideoAd object instance can be retrieved using the GADRewardBasedVideoAd.sharedInstance() method. Add a call to this method in the viewDidLoad: method of the ViewController.swift and save the reference to a private instance variable. It's important to note, you must include the import Firebase statement before calling any Firebase methods.

import Firebase

...

/// The reward-based video ad.
var rewardBasedVideo: GADRewardBasedVideoAd?

...

override func viewDidLoad() {
 super.viewDidLoad()
  // Get reference to shared instance GADRewardBasedVideoAd object
 rewardBasedVideo = GADRewardBasedVideoAd.sharedInstance()
  ...

 startNewGame()
}

GADRewardBasedVideoAdDelegate notifies you of rewarded video lifecycle events. You are required to set the delegate before loading an ad.

Set GADRewardBasedVideoAd delegate

GADRewardBasedVideoAd has a singleton design, so you will need to set a delegate on the shared instance, as shown below.

class ViewController: UIViewController, GADRewardBasedVideoAdDelegate
...

  override func viewDidLoad() {
   super.viewDidLoad()
   rewardBasedVideo = GADRewardBasedVideoAd.sharedInstance()
   rewardBasedVideo?.delegate = self
   ...

   startNewGame()
  }
...

The most important event in this delegate is rewardBasedVideoAd:didRewardUserWithReward:, which is called when the user should be rewarded for watching a video. You may optionally implement other methods in this delegate.

In rewardBasedVideoAd:didRewardUserWithReward:, you will reward the user for watching the ad by incrementing the coin count by the reward amount. For other delegate methods, you can add simple print statements.

// MARK: GADRewardBasedVideoAdDelegate implementation

func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
 didRewardUserWith reward: GADAdReward) {
 print("Reward received with currency: \(reward.type), amount \(reward.amount).")
 earnCoins(NSInteger(reward.amount))
}

func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
 didFailToLoadWithError error: Error) {
 print("Reward based video ad failed to load: \(error.localizedDescription)")
}

func rewardBasedVideoAdDidReceive(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
 print("Reward based video ad is received.")
}

func rewardBasedVideoAdDidOpen(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
 print("Opened reward based video ad.")
}

func rewardBasedVideoAdDidStartPlaying(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
 print("Reward based video ad started playing.")
}

func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
 print("Reward based video ad is closed.")
}

func rewardBasedVideoAdWillLeaveApplication(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
 print("Reward based video ad will leave application.")
}

The next step to monetizing your app with rewarded video ads is making the ad request. Ad requests should be made to the singleton GADRewardBasedVideoAd instance. It is best practice to call load:withAdUnitID as early as possible so we'll make this call in the startNewGame: method, which is invoked at the beginning of every game.

fileprivate func startNewGame() {
 gameState = .playing
 counter = gameLength
 playAgainButton.isHidden = true

 // Load a reward based video ad.
 rewardBasedVideo?.load(GADRequest(),
  withAdUnitID: "ca-app-pub-3940256099942544/1712485313")

 ...
}

For your app to present the user with the option to watch an ad, you will need to modify the app's Main.Storyboard file to add an additional UIButton, to present the user with the option to watch the rewarded video ad.

After selecting the Main.storyboard file, in the bottom-right corner, select a UIButton element and drag it into your view controller. Then modify the button settings and placement to those shown below.

Once you've created the UIButton, you will need a reference to it in your code. Open up the Assistant Editor by navigating to View > Assistant Editor > Show Assistant Editor. Make sure the ViewController.swift file is showing in the Assistant Editor (the right pane of the screen). Next, holding the control key, click the newly created UIButton (in the center pane), and drag your cursor over to ViewController.swift (as indicated by the blue line going from the center pane to the right pane).

When prompted, configure the IBOutlet as shown below.

Set click action

Next, you need to configure the code to be invoked when the button is pressed. To do so, repeat the process of holding the control key, clicking the newly created UIButton, and dragging your cursor over to ViewController.swift.This time you'll will set the connection as an action instead of an outlet, as shown below.

Within the generated showAd: method, you will need to invoke present:fromRootViewController: method on the singleton GADRewardBasedVideoAd object to display the rewarded video ad.

@IBAction func showAd(_ sender: Any) {
 if rewardBasedVideo?.isReady == true {
  rewardBasedVideo?.present(fromRootViewController: self)
 }
}

Handle visibility of show ad button

Currently, the button presenting with the user with the option to watch a rewarded video ad is always visible. However, we only want this button to be visible at the end of the game. Let's start by hiding this button at the beginning of every game, as shown below.

private void startGame() {
  ...
  playAgainButton.isHidden = true
  watchAdButton.isHidden = true
  ...
}

Now, we'll want to make this button visible at the end of a game if an ad has loaded and is ready to be shown. This can be determined by checking the isReady property on the GADRewardBasedVideoAd object.

fileprivate func endGame() {
 ...
 playAgainButton.isHidden = false
 if rewardBasedVideo?.isReady == true {
   watchAdButton.isHidden = false
 }
 ...
}

Your app is now ready to display rewarded video ads using the Google Mobile Ads SDK. Run the app and once the countdown timer has expired, you should be presented with the option to watch an ad for additional coins.

What we've covered

Next Steps

Learn More

TRY IT