How to integrate AdMob ads with SwiftUI

Michael Barney Jr
3 min readOct 22, 2019

--

After painstaking hours trying to figure out how to implement Ads into my SwiftUI app by converting the UIKit documentation, I thought it was only fair to share the solutions that I found.

For full disclosure, I don't think these are the best solutions. The code is available in this GitHub repository so you can update it with more robust solutions.

Anyway, here we go!

The First Step

To start off, head to Google AdMob and either create your account or create a new Ad Unit. This is the standard process for any development framework and can be followed using this first page of the documentation which handles the CocoaPod installation and AdMob configuration.

The next step is configuring the individual Ad Units. This gets tricky to follow because the documentation is either in standard Swift UIKit or even in Objective-C.

Banner Ads

This is the ad that is continuously show in the screen, normally at the bottom.

The documentation asks for a View Controller and I couldn't find a workaround for this, so my solution implements a UIViewControllerRepresentable which initialises the banner's UIKit view.

Then, I created a standard SwiftUI view to facilitate its modular use.

(Remember to switch bannerID with your AdMob banner ad unit ID)

And voila! Now you can just add Banner() anywhere in your SwiftUI's view body code for it to appear once it's loaded, just remember that the ad will not appear on the SwiftUI simulator.

Interstitial Ads

For Interstitials, I found that it was actually really simple to implement.

(Remember to switch interstitialID with your AdMob interstitial ad unit ID)

I created the Interstitial class with all of the implementations. Then you can just reference it in your SwiftUI view and call the showAd() method right after a transition for you Ad to appear.

In the showcased example, the SwiftUI ContentView has a button that when clicked triggers the Interstitial to appear.

Rewarded Ads

This was tricky, but I think I found a nice solution.

(Remember to switch rewardID with your AdMob rewarded ad unit ID)

Like interstitial, I created the Rewarded class with the implementations. To use it, just reference it in your SwiftUI view and call the showAd() method, now passing an action to be performed once the user has seen the entire ad, giving to the user the "reward".

Conclusion

I really liked how modular this solution turned out. I also really liked how SwiftUI made the Banner really made it simple for further uses, just by adding one command for the whole ad to show however you like it.

If you have any questions or suggestions, feel free to leave a comment or follow my Instagram to keep in touch. Also, the app that I implemented these ads is in the App Store so you can see how it turned out.

--

--

Michael Barney Jr

Desenvolvedor apaixonado por Produtos Digitais e Plataformas Conversacionais 🤖