Engineering

UI.guardAsync and UI.GuardAsyncAfter

Sometimes, In iOS App Development, To display correctly, there are times use dispatch async.

This approach is a not good approach. Because It makes some side-effects.

For example, Tap the button to display ViewController.
If displaying ViewController is implemented asynchronously, the user can double tap.
Then, ViewController will show twice.

If you use dispatch async unavoidably, you need to disable user interface until complete task.

I created short utility for this approach.

public enum UI {

  public static func guardAsync(execute: @escaping () -> Void) {
    UIApplication.shared.beginIgnoringInteractionEvents()
    DispatchQueue.main.async {
      UIApplication.shared.endIgnoringInteractionEvents()
      execute()
    }
  }

  public static func guardAsyncAfter(deadline: DispatchTime, execute: @escaping () -> Void) {
    UIApplication.shared.beginIgnoringInteractionEvents()
    DispatchQueue.main.asyncAfter(deadline: deadline) {
      UIApplication.shared.endIgnoringInteractionEvents()
      execute()
    }
  }
}
func tapButton() {
  UI.guardAsync {
    // to do something
  }
}