Search code examples
iosswiftactivity-indicator

Activity Indicator not appearing


I have some heavy code that runs for around 0.2 seconds.

I set up the activity indicator like this; however, it doesn't show up, but rather the whole screen freezes for around 0.2seconds until the code finishes.

func heavyWork() {
    self.actvityIndicator.startAnimating()

    ...
    // heavy loop codes here
    ...

    self.activityIndicator.stopAnimating()
}

Is this the correct way of using the activity indicator?

When I comment out

// self.activityIndicator.stopAnimating()

the activity indicator shows up and stays there - the codes are set up right.

But UI doesn't seem to be updated at the right time.

As i said, the screen just freezes without showing the activity indicator until the heavy code is done.


Solution

  • maybe you want to carry on with such pattern instead:

    func heavyWork() {
        self.actvityIndicator.startAnimating()
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
    
            // ...
            // heavy loop codes here
            // ...
    
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.activityIndicator.stopAnimating()
            })
        });
    }
    

    as the heavy work should happen in a background thread and you need to update the UI on a main thread after.


    NOTE: obviously it is assumed you call the func heavyWork() on a main thread; if not, you might need to distract the initial UI updates to the main thread as well.