Dismiss UIAlertView after 5 Seconds Swift

后端 未结 10 1787
悲哀的现实
悲哀的现实 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:52

    A solution to dismiss an alert automatically in Swift 3 and Swift 4 (Inspired by part of these answers: [1], [2], [3]):

    // the alert view
    let alert = UIAlertController(title: "", message: "alert disappears after 5 seconds", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)
    
    // change to desired number of seconds (in this case 5 seconds)
    let when = DispatchTime.now() + 5
    DispatchQueue.main.asyncAfter(deadline: when){
      // your code with delay
      alert.dismiss(animated: true, completion: nil)
    }
    

    Result:

提交回复
热议问题