0

I'm trying to present an alert after user logs out. I want this to disappear after, let's say, 3 seconds. I've followed some solution on UIAlert in Swift that automatically disappears?

Following is my code. The problem I'm facing is that after user logs out the I'm navigating away to another view (Home VC) hence I'm getting error:

dismissAlert]: unrecognized selector sent to instance

How do I make it work in this scenario?

let alert = UIAlertController(title: "", message: "Logged out", preferredStyle: .alert)

let cancelAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)

alert.addAction(cancelAction)

UIApplication.shared.keyWindow?.rootViewController!.present(alert, animated: true, completion: nil)

_ = Timer.scheduledTimer(timeInterval: Double(3), target: self, selector: Selector(("dismissAlert")), userInfo: nil, repeats: false)
Vaughn
  • 375
  • 1
  • 3
  • 8

2 Answers2

1

What about using scheduledTimer with block which is called after time interval? I think this solution is Swift-ier then using selector

let alert = UIAlertController(title: "", message: "Logged out", preferredStyle: .alert)
...
Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { _ in
    alert.dismiss(animated: true)
    // code from dismissAlert if it is necessary
}
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40
0

you have to declare your method like that

_ = Timer.scheduledTimer(timeInterval: Double(3), target: self, selector: #selector(dismissAlert), userInfo: nil, repeats: false)

@objc func dismissAlert() {
    // your works
}
Ankur Lahiry
  • 2,253
  • 1
  • 15
  • 25
  • Tx I got it working finally. There is extra ) in #selector(dismissAlert)) in your answer. Can you please fix it? – Vaughn Feb 09 '19 at 18:09