Search code examples
ioschartsios-chartsviewdidappear

Where to call function Fill Chart Array to reduce loading time?


I am using iOS-Charts and I have a ViewController where I call the function that fills the data for the chart.

Currently I call it in from ViewDidAppear, but it takes quite long to load. Where is the best place to call it?


Solution

  • If you put expensive loading code in viewDidAppear it won't run until your view controller is fully onscreen. If possible you probably want to do this in viewDidLoad, since this is called before your view controller is onscreen. It will also only be called once during the view controller's initial setup, while viewDidAppear can be called many times if you're navigating away from / back to this view controller.

    Response to Comment

    The problem is that you're doing expensive work on the main thread / queue. So the thread of execution gets to your viewDidLoad and then everything has to wait for your work to finish before your function can exit and your view controller can be presented. What you want to do if possible is to perform your work asynchronously, on a separate queue, and then update your screen on the main thread when the work is complete:

    override func viewDidLoad() {
        super.viewDidLoad()
        DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
            let results = someExpensiveOperation()
            DispatchQueue.main.async {
                updateViewWithResults(results)
            }
        }
    }