Skip to content

Instantly share code, notes, and snippets.

@MichaelBarney
Last active March 15, 2022 03:45
Show Gist options
  • Save MichaelBarney/af66902172cb5d595795b5633522fc71 to your computer and use it in GitHub Desktop.
Save MichaelBarney/af66902172cb5d595795b5633522fc71 to your computer and use it in GitHub Desktop.
A google AdMob Banner implementation in SwiftUI
import SwiftUI
import GoogleMobileAds
import UIKit
final private class BannerVC: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIViewController {
let view = GADBannerView(adSize: kGADAdSizeBanner)
let viewController = UIViewController()
view.adUnitID = bannerID
view.rootViewController = viewController
viewController.view.addSubview(view)
viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
view.load(GADRequest())
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
struct Banner:View{
var body: some View{
HStack{
Spacer()
BannerVC().frame(width: 320, height: 50, alignment: .center)
Spacer()
}
}
}
struct Banner_Previews: PreviewProvider {
static var previews: some View {
Banner()
}
}
import SwiftUI
import GoogleMobileAds
import UIKit
final class Interstitial:NSObject, GADInterstitialDelegate{
var interstitial:GADInterstitial = GADInterstitial(adUnitID: interstitialID)
override init() {
super.init()
LoadInterstitial()
}
func LoadInterstitial(){
let req = GADRequest()
self.interstitial.load(req)
self.interstitial.delegate = self
}
func showAd(){
if self.interstitial.isReady{
let root = UIApplication.shared.windows.first?.rootViewController
self.interstitial.present(fromRootViewController: root!)
}
else{
print("Not Ready")
}
}
func interstitialDidDismissScreen(_ ad: GADInterstitial) {
self.interstitial = GADInterstitial(adUnitID: interstitialID)
LoadInterstitial()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment