How to get the UIViewController instance for displaying dialog when the app starts up?

Hi! iOS/MacOS developers,

I am trying to integrate a SDK to my iOS app, and I need to call a function provided by the SDK when the app starts running, to display a dialog.

My iOS app is developed with SwiftUI. For now, I attempt to add the code to the didFinishLaunchingWithOptions delegate of the AppDelegate.swift file, like the following:

import MoPubSDK
// ...
// Check whether you must show the consent dialog
MoPub.sharedInstance().shouldShowConsentDialog;
MoPub.sharedInstance().loadConsentDialog(){ 
   a in MoPub.sharedInstance().showConsentDialog(
           from: myUIViewController, completion: nil)}

However, I don't know how I can get the myUIViewController variable.

My questions are:

  1. how can I get a UIViewController instance when the app starts, such that I can pass it into the SDK function for dialog display?
  2. If it is not possible to do it in AppDelegate.swift, can it be done some where else?

Thank you!

how can I get a UIViewController instance when the app starts, such that I can pass it into the SDK function for dialog display?

If it is not possible to do it in AppDelegate.swift, can it be done some where else?

If your project have an automatically generated SceneDelegate.swift, you may do it in it. But it is hard to say if it really would work or not, without knowing what showConsentDialog does and how your project is organized.

Hi OOper,

Thank you for your suggestion about using Life Cycle as UIKit App Delegate. I will try it. On another hand, I found a way to get a UIViewController object from ContentView.swift file, like the code below. Is this solution Ok? or there will be issue?

Thank you!

import SwiftUI
import MoPubSDK

struct ContentView: View {
    var body: some View {
        return

        Text("Hello, world!")
            .padding()

            .onAppear(){
                // for MoPub: Check whether you must show the consent dialog
                let shouldShow = MoPub.sharedInstance().shouldShowConsentDialog;
                // for MoPub: Start loading the consent dialog. This call fails if the user has opted out of ad personalization
                let myUIViewController : UIViewController = (UIApplication.shared.windows.first?.rootViewController)!
                MoPub.sharedInstance().loadConsentDialog(){ a in
                    MoPub.sharedInstance().showConsentDialog(from: myUIViewController, completion: nil)
                }
            }
    }
}

Hi OOper,

For the "UIKit App Delegate" option of Life Cycle, I found it is only available if I chose "iOS" App template for the new project. If I chose "Multiplatform" template, then there is no Life Cycle choices for me to select.

Thank you!

How to get the UIViewController instance for displaying dialog when the app starts up?
 
 
Q