Search code examples
swiftanimationdispatch-queue

Swift - stopAnimating() - must be used from main thread only


I have a succession of tasks that have to be performed in sequence, so they are corralled by DispatchQueue. To inform the user that they are chugging away I start the activity icon. But how do I stop if off the main thread?

Logically what I am trying to achieve is:

override func viewDidLoad() {
   super.viewDidLoad()    
   self.activityIcon.startAnimating()

   DispatchQueue.main.async {
      self.bigTask1()   
   }

   DispatchQueue.main.async {
      self.bigTask2()  
      self.activityIcon.stopAnimating() 
   }
}

This obviously generates the runtime error: " UIActivityIndicatorView.stopAnimating() must be used from main thread only".

Putting the stopAnimating() in the main queue turns it on and off so fast no one will ever see it.

What is the approved way call functions like this off the main queue?

Many thanks. P.s. I have read answers of similar questions on SO but don't quite get them.


Solution

  • You can do big task in default background queue, and when the big task completes then simply get the main queue and perfom any UI Updates.

    override func viewDidLoad() {
       super.viewDidLoad()
    
       self.activityIcon.startAnimating()
    
       DispatchQueue.global().async {
          self.someBigTask()
    
          DispatchQueue.main.async {
             self.activityIcon.stopAnimating()
          }
       }
    
    }
    

    Hope you will find this helpful.