SwiftUIでインタースティシャル広告を実装する方法
インタースティシャル用のクラスを用意
import GoogleMobileAds
#if DEBUG
let adUnitID = ""
#else
let adUnitID = ""
#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!)
}
}
SWiftuiのボタン押下時に呼び出し
変数は用意してください
//保存ボタン
Button(action:{
self.showingAlert = true
}){
Image(systemName: "tray.and.arrow.down")
Text("保存")
}
.padding(.trailing)
.alert(isPresented: $showingAlert) {
Alert(title: Text("保存しますか"),
primaryButton: .cancel(Text("キャンセル")),
secondaryButton: .default(Text("保存"),
action: {
interstitial.showAd()
}))
}