I made an app in Swift with SwiftUI framework and SwiftUI App life cycle.
I use that class to manage the interstitial ad:
class Interstitial : NSObject, GADFullScreenContentDelegate, UIApplicationDelegate{
var interstitial : GADInterstitialAd?
let adUnitID: String = "ca-app-pub-3940256099942544/4411468910"
override init() {
super.init()
loadInterstitial()
}
func loadInterstitial(){
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID: adUnitID, request: request) { [self] (ad, err) in
if(err != nil){
print(String(describing:err?.localizedDescription))
}
else {
interstitial = ad
interstitial?.fullScreenContentDelegate = self
}
}
}
func showAd(){
let root = UIApplication.shared.windows.first?.rootViewController
if interstitial != nil {
interstitial!.present(fromRootViewController: root!)
}
else {
nc.post(name: Notification.Name("UserClosedAd"), object: nil)
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("ad closed")
nc.post(name: Notification.Name("UserClosedAd"), object: nil)
return
}
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
print(error.localizedDescription)
print("ad failed to be presented")
nc.post(name: Notification.Name("UserClosedAd"), object: nil)
return
}
func adDidPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
print("ad presented")
return
}
}
and I show the ad in this way:
let pub = NotificationCenter.default
.publisher(for: NSNotification.Name("UserClosedAd"))
var interstitial : Interstitial = Interstitial()
var body: some View {
Button(action:
{
self.interstitial.showAd()
}) {
Image(systemName: "text.bubble")
.foregroundColor(.red)
Text("Show ad")
}
.font(.system(size: 30, weight: .semibold, design: .rounded))
.padding(30)
.onAppear(perform: {
interstitial.loadInterstitial()
})
.onReceive(pub, perform: { _ in
newView = true
print("Ad closed")
})
}
The problem is that sometime the callback work, but other not. When I use the app on a real device, or simulator, that is not connected to Xcode, the callback never works.
What could be the problem?
Thanks in advance, Onnwen