Search code examples
swiftxcodeswiftuiadmobappdelegate

How to add code to AppDelegate using SwiftUI Life Cycle


I'm following Google's tutorial on how to integrate AdMob ads into my app. In the tutorial, they put some code into the App Delegate. I've only ever used the SwiftUI life cycle for apps, so I'm not even sure what the App Delegate is. However, the issue is that in the tutorial, they instruct to put this code in the App Delegate file:

[[GADMobileAds sharedInstance] startWithCompletionHandler:nil];

I'm trying to put this code into the init() of my app (aka the SwiftUI version of putting it into my App Delegate). However, as this doesn't seem to be Swift code, I can't use that line of code without receiving errors. What should I do to insert this code into my app init()?

Following this tutorial at around 3:10 into the video.


Solution

  • The init might be too early, try in app delegate as follows

    import GoogleMobileAds
    
    class AppDelegate: NSObject, UIApplicationDelegate {
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
            
            GADMobileAds.sharedInstance().start(completionHandler: nil) // << here !!
            return true
        }
    }
    
    @main
    struct YourApp: App {
    
        @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }