Search code examples
iosswiftdelayuialertviewuiactivityindicatorview

Activity indicator ignores delay function


This is function for showing activity indicator

func showActivityIndicator() {
     let container: UIView = UIView()
     container.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
     container.backgroundColor = .clear
     activityView.center = self.view.center
     container.addSubview(activityView)
     self.view.addSubview(container)
     activityView.startAnimating()
}

And this is delay function, parameter should be a number of seconds:

func delay(_ delay: TimeInterval, callback: @escaping ()->()) {
    let delay = delay * Double(NSEC_PER_SEC)
    let popTime = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC);
    DispatchQueue.main.asyncAfter(deadline: popTime, execute: {
        callback()
    })
}

This is the place of calling those two functions:

showActivityIndicator()
delay(3) {
    self.activityView.stopAnimating()
}
let alert = UIAlertController(title: "Success", message: "Thanks", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: {(alert: UIAlertAction!) in self.displayHomeVC()})
alert.addAction(action)

So my wish is to show activity indicator for 3 seconds and then show alert.
Problem : Activity indicator disappears after a moment and alert appears. Anyone know why?


Solution

  • Firstly what @Paulw11, and @matt said is true you should look into that.

    After you fix it you will bump a different problem, the alert isn't part of your callback. You should put the alert inside the "delay" func callback as follows:

    delay(3) {
        self.activityView.stopAnimating()
        let alert = UIAlertController(title: "Success", message: "Thanks", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: {(alert: UIAlertAction!) in self.displayHomeVC()})
        alert.addAction(action)
    }