Swift activity indicator only appears some of the time

156 Views Asked by At

The function takes a couple of seconds to complete, and about half of the time when I press the button, the activity indicator appears on the screen until the function is finished, like it is supposed to. The other half of the time, the screen just freezes while it goes through the function and the activity indicator never appears.

    @IBAction func buttonAction(_ sender: Any) {
        activityIndicator.startAnimating()
            DispatchQueue.global(qos: .default).async {
                DispatchQueue.main.async {
                    self.function()
                    self.activityIndicator.stopAnimating()
                }
            }
    }
1

There are 1 best solutions below

0
Ptit Xav On BEST ANSWER

I think function should not be executed in main queue :

   @IBAction func buttonAction(_ sender: Any) {
    activityIndicator.startAnimating()
        DispatchQueue.global(qos: .default).async {
            self.function()
            DispatchQueue.main.async {
              self.activityIndicator.stopAnimating()
            }
        }
}