Integrating iAds into an iOS 8 App using Swift

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
An iOS 8 Sprite Kit Particle Emitter TutorialIntegrating Maps into iOS 8 Applications using MKMapItem and Swift


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


In terms of revenue generation options, the iTunes App Store eco-system provides a number of options. Perhaps the most obvious source of revenue for app developers involves charging the user an upfront fee for the application. Another option involves a concept referred to as “in-app purchase” whereby a user buys something from within the installed and running application. This typically takes the form of virtual goods (a packet of seeds in a farming simulation or a faster car in a racing game) or premium content such as access to specific articles in a news application. Yet another option involves the inclusion of advertisements in the application. It is, of course, also common to generate revenue from a mixture of these three options.

The subject of this chapter involves the use of advertising, specifically using Apple’s iAds system to incorporate adverts into iOS 8 based applications.


Contents


Preparing to Run iAds within an Application

In order to receive revenue from iAds advertising that you place in your applications it is important to accept the iAd Network terms and conditions. This is achieved by logging into the iTunes Connect portal at itunesconnect.apple.com using your Apple ID, clicking on the Contracts, Tax and Banking link and following the instructions to set up the agreements and to enter the necessary tax and banking information.

iAd Advertisement Formats

The iAds platform supports four different advertising formats consisting of banner, interstitial, medium rectangle and pre-roll video, each of which can be implemented within an iOS application using just a few lines of code.


Banner ads are supported on both iPhone and iPad based applications and are intended to appear at the bottom of the device display while an application view is visible to the user. When a banner ad is tapped, a full screen advert appears until dismissed by the user. For as long as the banner is visible and the device has internet connectivity, the banner will cycle through different ads.

All that is required to make a banner ad appear on a view is to set the canDisplayBannerAds property of the corresponding view controller to true. For example:

override func viewDidLoad() {
    super.viewDidLoad()
    self.canDisplayBannerAds = true
}

When this property is enabled, iAds will rename the view property of the view controller to originalContentView and request a banner ad from the iAds ad server. In the event that an ad is available from the iAds inventory, the originalContentView will be resized to make space for the banner and the banner will be displayed.

Banner ads may be disabled at any time by turning off the canDisplayBannerAds property:

self.canDisplayBannerAds = false

As previously described, when the user taps on a banner a full screen advert will appear obscuring the current view. This advert will remain on the screen until dismissed by the user. Depending on the type of application, it may be necessary to take action when the banner is tapped. If the app is playing a video, for example, it would be prudent to pause playback while the view is obscured by the ad and subsequently resume once the user dismisses the ad. Such functionality can be achieved by overriding the viewWillDisappear and viewWillAppear delegate methods within the view controller code. These methods will then be called when the ad appears and disappears respectively:

override func viewWillAppear(animated: Bool) {
    // View is about to be obscured by an advert. 
    // Pause activities if necessary
}

override func viewWillDisappear(animated: Bool) {
    // Advert has been dismissed. Resume paused activities
}

Interstitial Ads

Interstitial adverts occupy the full device display and are primarily intended to be displayed when a user transitions from one screen to another within an application. When a transition is taking place from one view controller to another, interstitial ad display can be enabled by setting the interstitialPresentationPolicy property of the destination view controller. When using storyboards this is best performed within the prepareForSegue method which is called immediately before the transition takes place. Interstitial display can be configured to be automatic or manual. The following code, for example, implements automatic interstitial advertising for a transition using the prepareForSegue method:

override func prepareForSegue(segue: UIStoryboardSegue, 
			       sender: AnyObject?) {

    let destination = segue.destinationViewController 
				as! UIViewController
    destination.interstitialPresentationPolicy = 
		ADInterstitialPresentationPolicy.Automatic
}

The following code, on the other hand, demonstrates how to manually display an interstitial ad:

destination.interstitialPresentationPolicy = 
             ADInterstitialPresentationPolicy.Manual

destination.requestInterstitialAdPresentation()

When using interstitial ads, it is recommended that the application be given an opportunity in advance of the transition to make ad requests to the iAds system. This prevents any delays when the time comes to display the ad during the transition. This can be achieved by making a call to the prepareInterstitialAds method of the UIViewController class. An ideal place to perform this task is within the didFinishLaunchingWithOptions method of the application delegate class, for example:

import UIKit
import iAd

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        UIViewController.prepareInterstitialAds()
        return true
    }
.
.
}

Medium Rectangle Ads

The medium rectangle ad is presented to the user in the form of a 300x250 pixel rectangle and is designed to be used within the content of a view. Medium rectangle ads are represented by instances of the AdBannerView class which must be assigned a delegate that conforms to the ADBannerViewDelegate protocol. These delegate methods are called to notify the application of whether or not an ad is ready to be displayed. It is the responsibility of these methods to position, display and hide the ad within the view as needed. For as long as the banner is visible and the device has internet connectivity, the banner will cycle through different ads.

The following code, for example, creates a medium rectangle ad instance and assigns the current class as the delegate:

let rectangleAdView = ADBannerView(adType: ADAdType.MediumRectangle)
rectangleAdView?.delegate = self
When an ad is ready to be displayed, the bannerViewDidLoadAd method of the delegate will be called, the responsibility of which is to display the ad within the current view. For example:
func bannerViewDidLoadAd(banner: ADBannerView!) {
    self.view.addSubview(banner)
    self.view.layoutIfNeeded()
}

Note that the above code does not attempt to position the ad rectangle. In a real world application code will need to be added so that the ad appears in the appropriate location on the view.

The rectangle ad will rotate through different ads as long as inventory is available. In the event that an ad is not available, or the device loses connectivity, the didFailToReceiveAdWithError: delegate method will be called so that the advert can be removed from the view until another ad is available to be displayed:

func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError 
						error: NSError!) {
    banner.removeFromSuperview()
    self.view.layoutIfNeeded()
}

As with the banner ad format, a full screen advertisement will be displayed in the event that the user taps on the rectangle ad. Once again, the viewWillDisappear and viewWillAppear delegate methods may be used to pause and resume the application if appropriate.

Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book

Pre-Roll Video Ads

For applications that make use of the iOS MediaPlayer Framework to play videos, this feature allows advertisement videos to be played before the actual video is played to the user. This simply involves calling the playPrerollAdWithCompletionHandler method of the media player instance. A completion handler is then called so that the playback of the actual video can be initiated when the ad has finished running. For example:

let url = NSURL(string: 
		"http://www.ebookfrenzy.com/ios_book/movie/movie.mov")

let player = AVPlayer(URL: url)
let playerController = AVPlayerViewController()
playerController.player = player

self.presentViewController(playerController, animated: true, 
					completion: nil)

playerController.playPrerollAdWithCompletionHandler({error in       
    player.play()
})

As with the interstitial ad format, Apple recommends preparing the application for pre-roll video ads at application launch time:

.
.
import AVKit
.
.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    AVPlayerViewController.preparePrerollAds()
    return true
}

Creating an Example iAds Application

In the remainder of this chapter we will work step by step through the creation of a simple iOS 8 application that includes banner, interstitial and rectangle based iAd advertisements. Begin this tutorial by launching Xcode and creating a new iOS application project named iAdDemo using the Single View Application template using the Swift language and with the Devices menu set to Universal.

Adding the iAds Framework to the Xcode Project

Once the new project has been created, the first step is to make sure the iAds Framework is included in the project. Failure to add this framework will result in the application crashing at runtime.

To add the iAds framework, select the iAdDemo target located at the top of the project navigator panel. In the center pane, select the Build Phases tab and unfold the Link Binary With Libraries panel. Click on the ‘+’ button to display a list of existing frameworks, locate and select iAd.framework and click the Add button. The iAd.framework will now appear in the frameworks list along with the other frameworks already included in the project.

Enabling Banner Ads

To enable banner ads, begin by selecting the ViewController.swift file, importing the iAd Framework and modifying the viewDidLoad method to enable banner ads on the view controller class:

import UIKit
import iAd

class ViewController: UIViewController {

    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.canDisplayBannerAds = true
    }
.
.
}

Run the application to verify that a banner ad appears along the bottom edge of the view as illustrated in Figure 67-1:

Ios 8 iads banner ad.png

Figure 67-1


When the banner appears, tap on it to see the full screen advertisement, then close the advert to revert to the application.

Adding a Medium Rectangle Ad

To add the medium rectangle, begin by selecting the ViewController.swift file and modifying it to reflect the fact that this class will now be implementing the ADBannerViewDelegate protocol and to declare a reference to an ADBannerView instance:

import UIKit
import iAd

class ViewController: UIViewController, ADBannerViewDelegate {

    var rectangleAdView: ADBannerView?
.
.
}

Return to the viewDidLoad method and add code to create the ad instance and to designate the view controller as the delegate:

override func viewDidLoad() {
    super.viewDidLoad()
    self.canDisplayBannerAds = true

    rectangleAdView = ADBannerView(adType: ADAdType.MediumRectangle)
    rectangleAdView?.delegate = self
}
Next, implement the delegate methods to add and remove the ad rectangle from the view:
func bannerViewDidLoadAd(banner: ADBannerView!) {
    self.view.addSubview(banner)
    self.view.layoutIfNeeded()
}

func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
    banner.removeFromSuperview()
    self.view.layoutIfNeeded()
}

Compile and run the application, at which point the medium rectangle ad should appear in the top left hand corner of the display as shown in Figure 67-2:


Ios 8 iad medium rectangle.png

Figure 67-2


Implementing an Interstitial Ad

The first step in demonstrating interstitial ads in action is to add a second scene to the storyboard and implement a segue to that scene from the first scene. Begin by selecting the Main.storyboard file and dragging and dropping a new View Controller instance from the Object Library so that it is positioned to the right of the existing view controller scene.

Next, drag and drop a Button view onto the center of the first view controller scene. With the button selected, use the Auto Layout Align menu to add horizontal and vertical Center in Container constraints.

Ctrl-click on the button and drag the resulting line to the second view controller scene. Release the line and select the show option from the resulting menu.

On completion of these settings, the storyboard should resemble that of Figure 67-3:


Ios 8 iad demo storyboard.png

Figure 67-3


In order to avoid any delay in loading the ad artwork, prepare the application for interstitial ads by modifying the AppDelegate.swift file to import the iAd file framework and to perform the preparation method call:

import UIKit
import iAd

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        UIViewController.prepareInterstitialAds()
        return true
    }
.
.
}

The last task is to add the prepareForSegue method to the ViewController.swift file to enable automatic interstitial ads for the transition to the destination view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let destination = segue.destinationViewController 
			as UIViewController
    destination.interstitialPresentationPolicy = 
			ADInterstitialPresentationPolicy.Automatic
}

Compile and run the application and, once loaded, tap on the button to transition to the second scene at which point the interstitial ad should appear (Figure 67 4):


Ios 8 iads interstitial.png

Figure 67-4

Configuring iAds Test Settings

In the real world, there will be situations where an ad is not available to be displayed to the user. This might be because Apple does not have a suitable ad available in its inventory, or simply because the device does not have an internet connection and cannot connect to the Apple ad server. It is important, therefore, to test that the application gracefully handles such situations. In recognition of this fact, iOS provides a mechanism for simulating the absence of ad inventory (otherwise known as the ad fill rate) while testing an application. These settings are accessible via the Developer section of the Settings app on the device. Settings are available to adjust the ad refresh rate and also, as illustrated in Figure 67 5, the fill rate.

In the event that the ad does not appear, keep in mind that it can take a while for the Ad to arrive from the server. If no ad appears after about a minute, it may be worth accessing the Developer settings on the device and changing the fill rate to 100%.


Ios 8 iads settings.png

Figure 67-5


Other options provided on this settings screen include the ability to adjust the frequency with which the ads refresh during testing and a mode to highlight ads that are clipped by other views within the user interface.

Summary

There are a variety of methods for generating revenue from an iOS application. Perhaps one of the more obvious solutions, aside from charging an upfront fee for the application, is to integrate advertising into the user interface. The iAds Framework provides an easy to use mechanism for the integration of advertisements sourced from Apple’s iAds inventory. This chapter has covered the basics of the iAds Framework and worked through the creation of an example application.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
An iOS 8 Sprite Kit Particle Emitter TutorialIntegrating Maps into iOS 8 Applications using MKMapItem and Swift