-1

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?

faris97
  • 332
  • 2
  • 17
  • You have divided by NSEC_PER_SEC instead of multiplying – Paulw11 Mar 22 '20 at 01:16
  • 1
    Your delay function is totally wrong. Here, try one that works: https://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861 – matt Mar 22 '20 at 01:24
  • @matt tried, the same problem – faris97 Mar 22 '20 at 01:39
  • The `delay` function is over-engineered. You should lose all of those `NSEC_PER_SEC` references. It’s just `func delay(_ delay: TimeInterval, callback: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: callback) }` – Rob Mar 22 '20 at 04:17

1 Answers1

1

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)
}
Aviv Frenkel
  • 271
  • 4
  • 10