似乎没有很多将 Google MobileAdsSDK 8.0 (iOS) 与 SwiftUI 结合使用的示例。到目前为止,我有一堂课Interstitial
import GoogleMobileAds
import UIKit
final class Interstitial:NSObject, GADFullScreenContentDelegate{
var interstitial:GADInterstitialAd!
override init() {
super.init()
LoadInterstitial()
}
func LoadInterstitial(){
let req = GADRequest()
GADInterstitialAd.load(withAdUnitID: "...", request: req) { ad, error in
self.interstitial = ad
self.interstitial.fullScreenContentDelegate = self
}
}
func showAd(){
if self.interstitial != nil {
let root = UIApplication.shared.windows.first?.rootViewController
self.interstitial.present(fromRootViewController: root!)
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
LoadInterstitial()
}
}
在我的 SwiftUI 视图中,我创建了一个局部变量Interstitial
,并在执行操作时调用该函数,但是当广告显示时,它会在调用运行showAd()
后立即停止代码。showAd()
所以我认为我需要以某种方式调用showAd()
,一旦广告被关闭,然后在视图中执行我的其余代码。正如您在上面看到的那样,Interstitial
该类是委托,但我如何“提醒”我的 SwiftUI 视图广告已被关闭,以便我可以执行其余代码?下面是我的观点。
import SwiftUI
struct MyView: View {
@Environment(\.managedObjectContext) var managedObjectContext
var interstitial : Interstitial = Interstitial()
var body: some View {
VStack{
//... Display content
}
.navigationBarItems(trailing:
HStack{
Button(action: actionSheet) {
Image(systemName: "square.and.arrow.up")
}
}
)
}
func showAd(){
interstitial.showAd()
}
func actionSheet() {
showAd()
let data = createPDF()
let temporaryFolder = FileManager.default.temporaryDirectory
let fileName = "export.pdf"
let temporaryFileURL = temporaryFolder.appendingPathComponent(fileName)
do {
try data.write(to: temporaryFileURL)
let av = UIActivityViewController(activityItems: [try URL(resolvingAliasFileAt: temporaryFileURL)], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
} catch {
print(error)
}
}
}