Vaughn
Vaughn

Reputation: 397

UIAlert in Swift that automatically disappears after logout

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)

Upvotes: 0

Views: 232

Answers (2)

Robert Dresler
Robert Dresler

Reputation: 11210

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
}

Upvotes: 1

Ankur Lahiry
Ankur Lahiry

Reputation: 2315

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
}

Upvotes: 0

Related Questions