如果没有互联网连接,我会弹出一个UIAlertController。当连接恢复时,我不知道如何正确地解除它。因为我每隔10秒检查一次,如果我这样做:
self.dismissViewControllerAnimated(true, completion: nil)
一旦警报视图被解除,这将在每个间隔关闭主视图。我试过了:
let alert = UIAlertController(title: "No internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertControllerStyle.Alert)
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
alert.dismissViewControllerAnimated(true, completion: nil)
} else {
print("Internet connection FAILED")
self.presentViewController(alert, animated: true, completion: nil)
}
但alert.dismissViewControllerAnimated(true, completion: nil)
不起作用。谢谢!
这对我有用:谢谢@OS_Binod和@Pyro
let alert = UIAlertController(title: "No internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertControllerStyle.Alert)
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
self.dismissViewControllerAnimated(false, completion: nil)
} else {
print("Internet connection FAILED")
alert.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController(alert, animated: false, completion: nil)
}
我想,问题是多次呈现UIAlertController并试图解雇UIAlertController的一个实例..因此你需要在呈现之前解除UIAlertController,如下所示
let alert = UIAlertController(title: "No internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: .alert)
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
alert.dismiss(animated: true, completion: nil)
} else {
print("Internet connection FAILED")
alert.dismiss(animated: true, completion: nil)
self.present(alert, animated: true, completion: nil)
}
我认为问题可能是你在显示警报之前试图解除警报
更新:如果你想在互联网恢复后才解除警报,请在显示“UIAlertController”后立即显示“UIAlertController”的引用
在你的情况下,你试图解除新创建的对象的“警报”,这个对象甚至没有显示,所以你需要在互联网回来之前关闭旧的保留参考的旧文件。
此外,如果您每隔10秒调用该方法,则在呈现新警报之前解除旧警报以避免多重警报,否则您可以在已经显示警报的情况下制作标记方法将不会每10秒再次检查一次,直到警报解除为止
更好的选择是:检查外面的互联网连接,如果没有互联网连接,那么只创建UIAlertController
更新1您可以将警报作为全局变量并在您在else块中创建警报对象时存储警报对象,并且当互联网返回时您可以检查警报是否具有对象,如果是,您可以关闭警报
if Reachability.isConnectedToNetwork() == true {
print("Internet connection OK")
if alert != nil {
alert.dismissViewControllerAnimated(true, completion: nil)
}
//dismiss the alert using old refence from the alert
//continue your normal code
} else {
alert = UIAlertController(title: "No internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertControllerStyle.Alert)
//you may check and dismiss the previous alertcontroller before presenting the new one
print("Internet connection FAILED")
self.presentViewController(alert, animated: true, completion: nil)
}