Search code examples
iosswiftuikituialertcontroller

Dismiss UIAlertController with timer


Dismiss a UIAlertController.Style.actionSheet after a couple of seconds if the OK button is not tapped.

I tried putting a timer right after presenting the actionSheet to call a method to dismiss it but it doesn't close it.

Here is my code:

func showActionSheet(){
    
    let alert = UIAlertController(title: "Some Tile", message: "Some Message", preferredStyle: UIAlertController.Style.actionSheet)

    alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.cancel, handler: {
        action in
        self.closeSheetView()
    }))

    self.present(alert, animated: true, completion: nil)

    timer = Timer.scheduledTimer(timeInterval: 2 , target: self, selector: #selector(self.closeSheetView), userInfo: nil, repeats: false)
}

@objc func closeSheetView(){
    self.dismiss(animated: true, completion: nil)
}

FYI - the closeSheetView method seems to get called but the sheet view doesn't close.


Solution

  • i just do it in my projrct without timer i use delay , may be it will work for you ...!

    let alert = UIAlertController(title: "", message: "alert disappears after 5 seconds", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)
    
    // here it work for 5 sec
    let when = DispatchTime.now() + 5
    DispatchQueue.main.asyncAfter(deadline: when){
      // your code with delay
      alert.dismiss(animated: true, completion: nil)
    }