我有一个UIViewController扩展,用于在任何视图控制器中显示警报。在这个奇怪的用例发生之前,它运行得很好:
extension UIViewController {
func showModal(title: String, msg: String, handler: ((UIAlertAction) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: handler))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
}
在视图控制器中,我点击一个按钮,该按钮触发网络获取:
@IBAction func didTapSave(_ sender: UIButton) {
Task {
let result = await BalanceManager.shared.fetchAllBalances()
switch result {
case .success(_):
self.showModal(title: "", msg: "account successfully saved") { (_) in
//This code always gets executed
self.navigationController?.popViewController(animated: true)
}
case .failure(let failure):
self.showModal(title: "", msg: "failure") { (_) in
//Code in here is not executed
print("Failure closure")
}
}
}
我不明白为什么在".failure“情况下,showModal的闭包不执行。如果我用self.showModal在行上设置了断点,那么代码就会到达那里,但当我点击弹出窗口上的"OK“时,代码就不会执行闭包了。
发布于 2022-10-10 19:02:42
我想出来了,是我的编程错误和睡眠不足。)另一个正在监听相同获取结果的通知的VC触发了一个弹出,尽管VC是不可见的,但它是活动的,嵌入在选项卡条控制器中。所以我的“失败”弹出从未被正确执行过。在用发送方参数更新showModal方法之后,我发现了这个问题,随后我添加了一个修复程序,要求调用的VC在它想显示弹出窗口时是可见的:
func showModal(sender: UIViewController, title: String, msg: String, handler: ((UIAlertAction) -> Void)? = nil) {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: handler))
DispatchQueue.main.async {
if sender.isVisible() {
self.present(alert, animated: true, completion: nil)
}
}
}
其中isVisible():
extension UIViewController {
func isVisible() -> Bool {
return self.isViewLoaded && self.view.window != nil
}
}
https://stackoverflow.com/questions/74007879
复制相似问题