Swift 中的 UIAlert 在注销后自动消失

UIAlert in Swift that automatically disappears after logout

我正在尝试在用户注销后显示警报。我希望它在比方说 3 秒后消失。我在 UIAlert in Swift that automatically disappears?

上遵循了一些解决方案

以下是我的代码。我面临的问题是,在用户注销后,我正在导航到另一个视图(主页 VC),因此出现错误:

dismissAlert]:无法识别的选择器发送到实例

如何让它在这种情况下工作?

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)

你必须这样声明你的方法

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

@objc func dismissAlert() {
    // your works
}

如何使用 scheduledTimer 和在时间间隔后调用的块?我认为这个解决方案是 Swift-然后使用选择器

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
}