How to run function when "viewDidLoad" is called while using SwiftUI

I'm trying to run a function when the app finish loading up, like viewDidLoad, but I'm using SwiftUI now and I have no viewDidLoad. How can I do this now?

var body: some View {
    NavigationView {
        Form {
            Section {
                self.exampleFunction()

                Text(" ......  ")
            }
        }
    }
}

I want to take some information from that function and present it in the text. But the way I'm doing it is wrong. It's not building.


Solution 1:

You can use .onAppear { ... } to execute arbitrary code when a view appears:

var body: some View {
        NavigationView {
            Form {
                Section {
                    Text(" ......  ")
                }.onAppear { self.exampleFunction() }

Solution 2:

If you're trying to run something after the app launches and has nothing to do with a specific view you can add code in two different places...

In AppDelegate.swift, the first function is called after the App launches...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        // ******** Run your function here **********

        return true
    }

Or in, SceneDelegate.swift, the first function actually sets the root view to the original ContentView...

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Use a UIHostingController as window root view controller
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: ContentView())
            self.window = window

        // ******** Add code here before root view is shown **********

            window.makeKeyAndVisible()

        // ******** Add code here after root view is shown **********

        }
    }