Dismiss UIAlertView after 5 Seconds Swift

后端 未结 10 1754
悲哀的现实
悲哀的现实 2020-12-22 20:31

I\'ve created a UIAlertView that contains a UIActivityIndicator. Everything works great, but I\'d also like the UIAlertView to disappear after 5 seconds.

Ho

10条回答
  •  臣服心动
    2020-12-22 20:38

    In iOS 8.0+ UIAlertController inherits from UIViewController, so, it is just that, a view controller. So, all the restrictions apply. That's why when there's a possibility that the view gets dismissed by the user, it's not entirely safe to try to dismiss it without proper checks.

    In the following snippet there's an example of how this can be achieved.

    func showAutoDismissableAlert(
          title: String?,
          message: String?,
          actions: [MyActionWithPayload], //This is just an struct holding the style, name and the action in case of the user selects that option
          timeout: DispatchTimeInterval?) {
    
      let alertView = UIAlertController(
          title: title,
          message: message,
          preferredStyle: .alert
      )
    
      //map and assign your actions from MyActionWithPayload to alert UIAlertAction
      //(..)
    
      //Present your alert
      //(Here I'm counting on having the following variables passed as arguments, for a safer way to do this, see https://github.com/agilityvision/FFGlobalAlertController) 
      alertView.present(viewController, animated: animated, completion: completion)
    
    
      //If a timeout was set, prepare your code to dismiss the alert if it was not dismissed yet
      if let timeout = timeout {
        DispatchQueue.main.asyncAfter(
           deadline: DispatchTime.now() + timeout,
           execute: { [weak alertView] in
                if let alertView = alertView, !alertView.isBeingDismissed {
                    alertView.dismiss(animated: true, completion: nil)
                }
            }
        }
    }
    

提交回复
热议问题