我正在WKWebView
加载注册表单,当用户填写注册表单并点击"注册"按钮时,它将被带到注册成功页面。
如果用户在点击"注册"按钮时失去网络连接,如何捕获无网络错误?
如果用户在加载注册表单之前未连接到网络,则以下代码有效:
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
if(error.localizedDescription == "The Internet connection appears to be offline.") {
print("Network error")
self.presentingViewController?.dismiss(animated: true, completion: {
let alert = UIAlertController(title: "No Network", message: "No network, please check your internet connection and try again.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK".localisedString(), style: .default, handler: nil))
let topC = AppConstants.getRootController().topMostViewController()
topC.present(alert, animated: true, completion: nil)
})
}
}
- 您首先关闭了当前
ViewController
,然后您正在尝试UIAlertController
鞋,也许这就是为什么它不起作用的原因,否则您的代码是正确的 -
尝试先显示
如下所示alert
,然后关闭当前ViewController
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { if(error.localizedDescription == "The Internet connection appears to be offline.") { print("Network error") let alert = UIAlertController(title: "No Network", message: "No network, please check your internet connection and try again.", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { ( _ ) in let topC = self.storyboard!.instantiateViewController(withIdentifier: "cal") as! cal self.present(topC, animated: true, completion: nil) } alert.addAction(ok) self.present(alert, animated: true) { self.presentingViewController?.dismiss(animated: true, completion: nil) } } }
-
试试这段代码,这将起作用(代码中缺少的内容如下(
-
ok
AlertAction 未添加到alert
AlertViewController 中 -
topC
已初始化,但未ok
操作中显示。
-