Travel, Technology, Health

How to use AdMob in an iOS App with Swift

February 16, 2016 / Eddy / Software Development, Swift

Apple will be officially discontinuing the iAd App Network on June 30, 2016 and is currently no longer accepting any new apps into the network. The avenue to monetise your free apps the Apple’s way will be gone. However, they are not the only way to monetize them, that’s where Admob from Google comes to the rescue. This is their Adsense for mobile apps.

The first thing to do is if you have not done so, is to sign up for an AdMob account, you can  do so at https://www.google.com/admob/ . Just go through the necessary details to Sign Up for an AdMob account. You will need set up an AdSense account and if you do not have one, the sign up process will guide you through it.

Once that is done, click on the Monetise New App button and there you can link the App by typing in your App Name or if it is a new app, just do it manually and select the platform the application is for. They currently support iOS, Android and Windows Phone 8.

The next thing is do is to go to the Monetise tab, click on your App name and add a New Ad Unit. Copy the Ad Unit ID as you will need that in your application code.

We are done with the technicality issues and now to some Swift coding in XCode. But before that, we will need to download the Google Mobile Ads framework which can be downloaded at https://developers.google.com/admob/ios/download

In XCode, just drop the entire GoogleMobileAds.framework to the app like below.

Screen Shot 2016-02-16 at 5.48.18 PM

The next thing is to drop a View to your Scene where you want the Ad to be in and change the Class under Custom Class to GADBannerView

Screen Shot 2016-02-16 at 6.03.36 PM

Remember the Long Ad Unit ID from Admob, here is where you put it in. Below I just added a fictitious code but the real one is actually pretty long. Under Autoload Enable, there is three options – Default / On / Off. If your app does not include an In-App Purchase to remove the ads then just set it to On or Default. Off will be useful if you need to check if the User has already purchase a remove ads option and to show the Banner if they have not.

Screen Shot 2016-02-16 at 6.11.34 PM

After which, just wire the new Banner View to an IBOutlet and add the Import GoogleMobileAds line in code.

What I did to hide the ad when the user have already purchase the option to have it remove and to show it when they have not. I just add the following code in viewDidLoad

 if canRemoveAds == false {

            let request : GADRequest = GADRequest()
            adView.rootViewController = self
            adView.loadRequest(request)

        } else

        {

            adView.removeFromSuperview()   

        }

It is pretty easy to make the necessary transition to Google’s Admob.

Tags: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*