How to implement an Interstitial Ad combined with a counter
For details how to subscribe for the Apple iAds program, please check my previous article about iAD integration.
1. Create the sample project:
2. Create the sample program flow:
Add a new UIViewController class to your project and name it TargetViewController:
Place a new UIViewController on the Storyboard and add a button to each ViewController
Add constraints to the buttons to centre them on the screen for each form factor, orientation and resolution:
Change type of the new view controller to TargetViewController:
Add a unwindFromTargetViewController method to your ViewController class:
Now implement the navigation between the ViewControllers: Control Drag the first button, move it to TargetViewController and create a segue to implement the navigation from ViewController to TargetViewController:
Control Drag the button in TargetViewController and move the mouse pointer to the Exit box of ViewController:
Select the unwindFromTargetViewController method:
As a result you see a segue under each ViewController:
More on segues in my previous tutorial about View Navigation.
3. Implement the iAd Integration
If you start the project you can navigate from the start screen to the second screen and back. Now I’ll implement the logic to show a fullscreen (interstitial) ad after each third navigation to the second screen.
Add the iAD framework to your project:
Open ViewController.swift:
At the top import the iAD framework and define a global counter:
var counter = 0
class ViewController: UIViewController {
Add this code to the viewDidLoad method to initialise the ads:
Implement the logic to open the ad after each third third navigation to the second screen inside of the prepareForSegue method:
Thats all! Apple takes care about ads loading and error handling and decides, if the ad is ready to show. It can happen that no ad is shown. For example, if you click to fast in this sample project no new ad is available.
You can download the sample code from my GitHub repository. That’s all for today.
Cheers,
Stefan