前提
iOSアプリにadmobをつけたいです。
iPhoneの場合は問題なく表示されますが、iPadでテストすると広告が表示されずにしばらくしてからクラッシュしてしまいます。
実現したいこと
iPadアプリにadmobのバナー広告をつけたい
発生している問題・エラーメッセージ
@mainのところに以下のエラーが出ます "Window container should not be nil"
該当のソースコード
Swift
1import SwiftUI 2import UIKit 3import GoogleMobileAds 4 5class AppDelegate: NSObject, UIApplicationDelegate { 6 func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { 7 GADMobileAds.sharedInstance().start(completionHandler: nil) 8 return true 9 } 10} 11 12 13@main 14struct Rieki_chanApp: App { 15 16 @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate 17 18 @StateObject private var modelData = ModelData() 19 20 var body: some Scene { 21 WindowGroup { 22 ContentView(modelData: ModelData()) 23 .environmentObject(ModelData()) 24 } 25 } 26} 27 28import SwiftUI 29import GoogleMobileAds 30 31struct AdmobBannerViewController: UIViewControllerRepresentable { 32 let adSize = GADAdSizeFromCGSize(CGSize(width:320, height:50)) 33 34 func makeUIViewController(context: Context) -> UIViewController { 35 let view = GADBannerView(adSize: adSize) 36 let viewController = UIViewController() 37 #if DEBUG 38 view.adUnitID = "ca-app-pub-3940256099942544/2934735716" 39 #else 40 view.adUnitID = "ca-app-pub-2346604556465954~4360180123" 41 #endif 42 view.rootViewController = viewController 43 viewController.view.addSubview(view) 44 viewController.view.frame = CGRect(origin: .zero, size: adSize.size) 45 view.load(GADRequest()) 46 return viewController 47 } 48 49 func updateUIViewController(_ uiViewController: UIViewController, context: Context) {} 50} 51 52struct AdmobBannerView: View { 53 var body: some View { 54 HStack { 55 Spacer() 56 AdmobBannerViewController().frame(width: 320, height: 50) 57 Spacer() 58 } 59 } 60} 61 62struct AdmobBannerView_Previews: PreviewProvider { 63 static var previews: some View { 64 AdmobBannerView() 65 } 66} 67 68import SwiftUI 69import UIKit 70import GoogleMobileAds 71 72 73struct ContentView: View { 74 @ObservedObject var modelData: ModelData 75 76 var body: some View { 77 VStack { 78 AdmobBannerViewController().frame(width: 320, height: 50) 79 } 80 } 81}
試したこと
adMob関係のソースコードはほとんど参考にさせていただいたサイトからのコピペで正直内容はほぼわかっておりません。
補足情報(FW/ツールのバージョンなど)
Xcode13.3
あなたの回答
tips
プレビュー