I am looking for a solution for pausing app activity, such as music, while an interstitial ad is being shown, and then listening for the "adDidDismissFullScreenContent" notification before restarting music, etc. The showAd() func is working, but because I am using SwiftUI I can't use the GADFullScreenContentDelegate directly.
struct ContentView: View {
var fullScreenAd: InterstitialAd?
init() {
fullScreenAd = InterstitialAd()
}
var body: some View {
Button("Show Ad") {
if fullScreenAd != nil {
fullScreenAd!.showAd()
// TODO: Pause activity until the ad has been dismissed.
}
}
}
}
final class InterstitialAd: NSObject, GADFullScreenContentDelegate {
var interstitial: GADInterstitialAd?
var adID = "ca-app-pub-3940256099942544/4411468910"
override init() {
super.init()
self.loadInterstitial()
}
func loadInterstitial() {
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID: adID,
request: request,
completionHandler: { [self] ad, error in
if let error = error {
print("Failed to load interstitial")
return
}
interstitial = ad
interstitial?.fullScreenContentDelegate = self
})
}
func showAd() {
if self.interstitial != nil {
guard let firstScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
return
}
guard let firstWindow = firstScene.windows.first else {
return
}
let root = firstWindow.rootViewController
self.interstitial?.present(fromRootViewController: root!)
}
else{
print("Not Ready")
}
}
// Tells the delegate that the ad dismissed full screen content.
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("Ad did dismiss full screen content.")
self.loadInterstitial()
}
}