Skip to content

Instantly share code, notes, and snippets.

@ForceGT
Created February 9, 2021 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ForceGT/77fd0615924f7886d456842c9afdd123 to your computer and use it in GitHub Desktop.
Save ForceGT/77fd0615924f7886d456842c9afdd123 to your computer and use it in GitHub Desktop.
Code snippet showing how to use AdMob with SwiftUI (updated for Jan 2021)
// First create a dedicated class for this
```
import SwiftUI
import GoogleMobileAds
class Interstitial : NSObject,GADFullScreenContentDelegate{
var interstitial : GADInterstitialAd = GADInterstitialAd.init()
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("Ad dismissed")
loadInterstitial()
}
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
print(error.localizedDescription)
}
let adUnitID: String = AdUnit.homeInterstitial.unitID
override init() {
super.init()
loadInterstitial()
}
func loadInterstitial(){
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID: adUnitID, request: request) { (ad, err) in
if(err != nil){
print(String(describing:err?.localizedDescription))
}
else{
//You can show straight away if you want
// My use case was using a Button
// self.showAd()
self.interstitial = ad!
self.interstitial.fullScreenContentDelegate = self
}
}
}
func showAd(){
let root = UIApplication.shared.windows.first?.rootViewController
self.interstitial.present(fromRootViewController: root!)
}
}
// And now in Content View whenever your are required to show the add
```
struct ContentView: View {
var interstitial : Interstitial = Interstitial()
var body: some View {
VStack {
Button("Tap Me"){
self.interstitial.showAd()
}
}
}
}
```
@ForceGT
Copy link
Author

ForceGT commented Feb 9, 2021

Just for the sake of screenshots

image

And a little video

Screen.Recording.2021-02-09.at.8.00.47.PM.mov

@ForceGT
Copy link
Author

ForceGT commented Feb 9, 2021

You can get test ids for all your units here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment