Arun
Arun

Reputation: 1528

how to display activity indicator view until a function is completely executed?

I am new to IOS and swift. I am stuck with an issue in displaying activity indicator.

// In the controller
DispatchQueue.global(qos: .background).async {
        DispatchQueue.main.async {
            self.activityIndicator.startAnimating()

        }

        Sync.performSync()
        DispatchQueue.main.async {
            self.activityIndicator.stopAnimating()

        }

    }


class Sync {
   static func performSync() {
     User.performUserSync()
     ItemBarcode.performIbSync()
     // few more sync functions
   }
}

class User {
    static func performUserSync(){
       Alamofire.request("\(baseUrl)/api/users", method: .get, headers: 
       headers).responseJSON { response in
       // Fetch code and insert to database
       }
    }
}

The problem is the activity indicator view just appears and disappears after 1-2secs. But I want it to be displayed until entire Sync.performSync() function is executed which will take some time. How do I code it that way?

Upvotes: 0

Views: 557

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

You have this problem because the network request you perform in performUserSync is an asynchronous request and hence performUserSync becomes an asynchronous function as well, meaning that it returns before it would finish execution.

You have several ways to solve this issue:

  1. Only call activityIndicator.stopAnimating() inside the completion handler of your Alamofire request inside performUserSync.
  2. Change performUserSync and all functions calling it to return a completion handler and stop the activity indicator inside the returned completion handler.
  3. Use a framework, such as PromiseKit to handle the asynchronous functions like normal functions with return values.

Upvotes: 2

Related Questions