点击 UITextField 时,键盘会按预期显示。然而,在显示插页式广告并返回到同一个 UITextField 后,键盘会将所有视图上推,导致某些视图从屏幕上消失。
我使用
@EnvironmentObject var adsViewModel: AdsViewModel
和 .simultaneousGesture(TapGesture().onEnded{ adsViewModel.showInterstitial = true })
来展示广告。
主视图:
@main
struct PertukApp: App {
let adsVM = AdsViewModel.shared
init(){
GADMobileAds.sharedInstance().start(completionHandler: nil)
GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = [GADSimulatorID]
}
var body: some Scene {
WindowGroup {
ContentView().environmentObject(adsVM)
}
}
广告经理:
class AdsManager: NSObject, ObservableObject {
private struct AdMobConstant {
static let interstitial1ID = "ca-app-pub-9877420063334339/6051084944"
}
final class Interstitial: NSObject, GADFullScreenContentDelegate, ObservableObject {
private var interstitial: GADInterstitialAd?
override init() {
super.init()
requestInterstitialAds()
}
func requestInterstitialAds() {
let request = GADRequest()
request.scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
GADInterstitialAd.load(withAdUnitID: AdMobConstant.interstitial1ID, request: request, completionHandler: { [self] ad, error in
if let error = error {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
return
}
interstitial = ad
interstitial?.fullScreenContentDelegate = self
})
})
}
func showAd() {
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
let root = windowScene.windows.last?.rootViewController {
if let fullScreenAds = interstitial {
fullScreenAds.present(fromRootViewController: root)
} else {
print("not ready")
}
}
}
func adDidRecordImpression(_ ad: GADFullScreenPresentingAd) {
}
func adDidRecordClick(_ ad: GADFullScreenPresentingAd) {}
func ad(_ ad: GADFullScreenPresentingAd, didFailToPresentFullScreenContentWithError error: Error) {
requestInterstitialAds()
}
func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
requestInterstitialAds()
}
func adWillDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {}
func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {}
}
}
class AdsViewModel: ObservableObject {
static let shared = AdsViewModel()
@Published var interstitial = AdsManager.Interstitial()
@Published var showInterstitial = false {
didSet {
if showInterstitial {
interstitial.showAd()
showInterstitial = false
} else {
interstitial.requestInterstitialAds()
}
}
}
}
这里有一个解决方法:
用
ProgressView
或类似符号呈现一个空视图。然后在 topViewController
上进行插播式当前通话。这可以防止弄乱rootViewController
。
我还在 GitHub 上提出了一个问题。请在那里投票/评论,以便 Google 认为需要修复它:https://github.com/googleads/googleads-mobile-ios-examples/issues/446