Created
February 9, 2021 14:29
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() | |
} | |
} | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just for the sake of screenshots
And a little video
Screen.Recording.2021-02-09.at.8.00.47.PM.mov