ios - 无法从单独的函数中解雇 UIAlertController

标签 ios swift3 uialertcontroller dismiss

我有一个没有按钮的 UIAlertController(我使用此警报作为请稍候一些数据加载消息),我在我的 View Controller 的 viewDidLoad 函数中显示。显示警报后,我运行一个从数据库中检索信息的函数,完成后我想解除警报,以便用户可以继续,但是警报似乎在运行后并未解除:

self.dismiss(animated: true, completion: nil)

我也尝试过将我的 uialertcontroller 作为参数传递给函数并运行以下行但没有成功:

alertController.dismiss(animated: false, completion: nil)

编辑:这是我的 viewDidLoad 函数以及应该解除警报的函数

override func viewDidLoad() {
    super.viewDidLoad()

    let alertController = UIAlertController(title: "Loading", message:
        "This might take a moment", preferredStyle: UIAlertControllerStyle.alert)

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

func hideAlert(alert: UIAlertController) {
let hideAlertController = { () -> Void in 
alertController.dismiss(animated: false, completion: nil)
}
FIRDatabase.database().reference().child("info").observeSingleEvent(of: .value, with: { (dataSnapshot) in
        DispatchQueue.main.async {
            hideAlertController()
        }
    })
}

最佳答案

在你的 ViewController 中试试这个:

var operationPerformed : Bool = false;
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning();
    // Dispose of any resources that can be recreated.
}

override func viewDidLoad() {
    super.viewDidLoad();
}
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated);
    if(!self.operationPerformed){
        let alertController = UIAlertController(title: "Loading", message:
            "This might take a moment", preferredStyle: UIAlertControllerStyle.alert);
        self.present(alertController, animated: true, completion: nil);
        self.performOperation(alertToBeClosedOnFinish: alertController);
    }
}

func performOperation(alertToBeClosedOnFinish: UIAlertController) {
    let hideAlertController = { () -> Void in
        alertToBeClosedOnFinish.dismiss(animated: false, completion: nil)
    }
    DispatchQueue.global().asyncAfter(deadline: .now() + 2, execute: {
        DispatchQueue.main.async {
            hideAlertController();
            self.operationPerformed = true;
        }
    });
}

想法是当它的所有者在层次结构中时显示警报 Controller ,如果我理解你的意思 - 你想调用它一次,所以你应该检查操作是否已经执行。

但这种方法的缺点是当您可以将进度 View 创建为 UIView 的子类并将其添加到 super View 或从 super View 中删除时,尝试使用警报 Controller 。此外,有很多 pod 可以帮助您实现这一目标。

最好的问候, 谢尔盖

关于ios - 无法从单独的函数中解雇 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43059266/

相关文章:

ios - 固定宽度 : how to set its height to keep its aspect? 的 UIImageView

ios - Swift - Google map 因 'unexpectedly found nil' 错误而崩溃

ios - 你如何找出一个对象的类型

ios - CLLocation Prompt 显示并在一瞬间消失

ios - TTNavigator 重启里面的应用程序

ios - Swift 中的条纹

ios - 如何让 XLPagerTabStrip 将选定的选项卡居中?

swift - 将 AFNetworking swift 2.3 模拟转换为 swift 3?

customization - 在 iOS 8 中自定义 UIAlertController 以包含 UITableView 等标准元素

ios - UIAlertController 关闭速度很慢