Dismiss UIAlertView after 5 Seconds Swift

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

    0 讨论(0)
  • 2020-12-22 20:57

    Create the alert object as a global variable. You can use a NSTimer for this purpose.

    var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
    
    
    func dismissAlert()
    {
        // Dismiss the alert from here
        alertView.dismissWithClickedButtonIndex(0, animated: true)
    
    }
    

    NOTE:

    Important: UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert.

    Reference : UIAlertView

    0 讨论(0)
  • 2020-12-22 21:01

    For swift 4 you can use this code

    let alertController = UIAlertController(title:"Alert",message:nil,preferredStyle:.alert)
    self.present(alertController,animated:true,completion:{Timer.scheduledTimer(withTimeInterval: 5, repeats:false, block: {_ in
        self.dismiss(animated: true, completion: nil)
    })}
    
    0 讨论(0)
  • 2020-12-22 21:02

    I'm not an expert but this works for me and I guess is easier

    let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
    present(alert, animated: true) {
       sleep(5)
       alert.dismiss(animated: true)
    }
    
    0 讨论(0)
提交回复
热议问题