AdMob is a popular mobile advertising platform developed by Google that helps developers monetize their mobile apps. In this blog post, we’ll walk through the steps to implement AdMob in a SwiftUI.
Prerequisites
Xcode: Ensure you have the latest version of Xcode installed on your development machine.
Google AdMob Account: Create an AdMob account if you don’t have one already.
iOS App Project: Have a SwiftUI-based iOS app project ready for integration.
Steps to Implement AdMob
Set Up Your AdMob Account
Log in to your AdMob account.
Create an AdMob app.
Select the platform (iOS) and provide the required details for your app (app name, etc.).
Create 5 ad units for the new app. The result will be as follows:
Integrating the AdMob SDK
Search for the Google Mobile Ads Swift Package GitHub repository and select the version of the Google Mobile Ads Swift Package you want to use:
importUIKitimportGoogleMobileAdsfinalclassBannerAdViewController:UIViewController{privateletbannerView:GADBannerView=GADBannerView()privateletadUnitId:Stringinit(adUnitId:String){self.adUnitId=adUnitIdsuper.init(nibName:nil,bundle:nil)}requiredinit?(coder:NSCoder){fatalError("init(coder:) has not been implemented")}overridefuncviewDidLoad(){super.viewDidLoad()bannerView.adUnitID=adUnitIdbannerView.rootViewController=selfview.addSubview(bannerView)}overridefuncviewDidAppear(_animated:Bool){super.viewDidAppear(animated)loadBannerAd()}overridefuncviewWillTransition(tosize:CGSize,withcoordinator:UIViewControllerTransitionCoordinator){super.viewWillTransition(to:size,with:coordinator)coordinator.animate(alongsideTransition:{_in},completion:{_inself.loadBannerAd()})}privatefuncloadBannerAd(){letframe=view.frame.inset(by:view.safeAreaInsets)letviewWidth=frame.size.widthbannerView.adSize=GADCurrentOrientationAnchoredAdaptiveBannerAdSizeWithWidth(viewWidth)bannerView.load(GADRequest())}}