[英]How do we wait and listen for an admob interstitial ad to be dismissed in a SwiftUI View?
我正在尋找一種解決方案,用於在顯示插頁式廣告時暫停應用程序活動(例如音樂),然后在重新啟動音樂等之前收聽“adDidDismissFullScreenContent”通知。showAd() 函數正在工作,但因為我使用 SwiftUI 我不能直接使用 GADFullScreenContentDelegate 。
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()
}
}
我通過通知中心找到了一個解決方案,如下:
第 1 步:擴展通知
extension NSNotification.Name {
static let onAdDidDismiss = Notification.Name("onAdDidDismiss")
}
第 2 步:從 InterstitialAd class 內部發布通知
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
NotificationCenter.default.post(name: .onAdDidDismiss, object: nil)
self.loadInterstitial()
}
第 3 步:根據需要在任何視圖上處理 OnReceive()
VStack {
...
}
.onReceive(NotificationCenter.default.publisher(for: .onAdDidDismiss)) { _ in
musicIsPlaying = true
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.