如何解决Google Ads 8.0 插页式 SwiftUI
似乎将 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)
}
}
}
解决方法
通过添加一个 excaping 闭包,您可以传递一个函数并执行所需的操作。
final class InterstitialAd: NSObject,GADFullScreenContentDelegate {
var completion: () -> Void
var interstitial: GADInterstitialAd!
init(completion: @escaping () -> Void) {
self.completion = completion
super.init()
LoadInterstitialAd()
}
func LoadInterstitialAd() {
let req = GADRequest()
GADInterstitialAd.load(withAdUnitID: Constants.AdmobIDs.saveImageBlockID,request: req) { ad,error in
self.interstitial = ad
self.interstitial.fullScreenContentDelegate = self
}
}
func show() {
if self.interstitial != nil {
let root = UIApplication.shared.windows.first?.rootViewController
self.interstitial.present(fromRootViewController: root!)
}
}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
LoadInterstitialAd()
completion()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。