How to log the time it took to for a view to load

Viewed 187

Is it possible to determine how long it took for a SwiftUI view to have loaded? When I say loaded, I mean all sub views within the view are fully rendered on the screen. Thanks!

1 Answers

You can get the time when the view is initialized, and the time when onAppear(perform:) is called. You can then calculate the difference in seconds.

The init() is called when the view is trying to be created/initialized. This will be the start date.

onAppear(perform:) is only called once the view has been rendered onto the screen. This means that you know all subviews have also been loaded, since the view will be a composition of its subviews. When this is called, this will be the end date.

Example:

struct ContentView: View {
    private let creationDate: Date

    init() {
        creationDate = Date()
    }

    var body: some View {
        VStack {
            Text("Hello world!")

            Text(String(timeConsumingCalculation()))
        }
        .onAppear {
            let interval = Date().timeIntervalSince(creationDate)
            print(interval)
        }
    }

    private func timeConsumingCalculation() -> Int {
        (1 ... 10_000_000).reduce(0, +)
    }
}

Result (when I ran it, will vary):

4.901658892631531
Related