Created
April 7, 2021 21:09
-
-
Save boraseoksoon/df723505a23e39231b5d098e592faad8 to your computer and use it in GitHub Desktop.
[SwiftUI] Admob Interstitial for SwiftUI
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
import SwiftUI | |
import GoogleMobileAds | |
import UIKit | |
#if DEBUG | |
let adUnitID = "yourUnitID" | |
#else | |
let adUnitID = "yourUnitID" | |
#endif | |
final class Interstitial: NSObject, GADFullScreenContentDelegate { | |
private var interstitial: GADInterstitialAd? | |
override init() { | |
super.init() | |
loadInterstitial() | |
} | |
func loadInterstitial(){ | |
let request = GADRequest() | |
GADInterstitialAd.load(withAdUnitID:adUnitID, | |
request: request, | |
completionHandler: { [self] ad, error in | |
if let error = error { | |
print("Failed to load interstitial ad: \(error.localizedDescription)") | |
return | |
} | |
interstitial = ad | |
interstitial?.fullScreenContentDelegate = self | |
} | |
) | |
} | |
/// Tells the delegate that the ad failed to present full screen content. | |
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) { | |
print("Ad did fail to present full screen content.") | |
} | |
/// Tells the delegate that the ad presented full screen content. | |
func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) { | |
print("Ad did present full screen content.") | |
} | |
/// Tells the delegate that the ad dismissed full screen content. | |
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) { | |
print("Ad did dismiss full screen content.") | |
loadInterstitial() | |
} | |
func showAd(){ | |
let root = UIApplication.shared.windows.first?.rootViewController | |
interstitial?.present(fromRootViewController: root!) | |
} | |
} | |
// import SwiftUI | |
// | |
// struct ContentView: View { | |
// var body: some View { | |
// Button("hello!") { | |
// interstitial.showAd() | |
// } | |
// } | |
// } | |
// | |
// | |
// | |
// Don't forget admob initialization at init point like AppDelegate or @main | |
// GADMobileAds.sharedInstance().start(completionHandler: nil) | |
// GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = ["yourdevicekey"] | |
// | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment