当 WKWebView loadRequest 失败时加载自定义错误 htmlString [英] Load custom error htmlString when WKWebView loadRequest fails

查看:28
本文介绍了当 WKWebView loadRequest 失败时加载自定义错误 htmlString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我调用了 WKWebViewInstance.loadRequest(url).如果没有可用的互联网,我想在 WKWebView 中加载错误消息.

In my controller I have a call to WKWebViewInstance.loadRequest(url). If there is no internet available, I want to load an error message in the WKWebView.

我发现

  func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) 

在 WKWEbView 导航失败且没有互联网连接时调用.当我在上述委托方法中调用 webView.loadHtmlString() 时,没有任何反应.

gets called when a WKWEbView navigation fails with no internet connection. When I make the webView.loadHtmlString() call inside the above delegate method, nothing happens.

如何在发出 WKWEbView 导航请求时检测没有网络连接并将修复的错误消息加载到 Web 视图中?

How do I detect the absence of network connection while WKWEbView navigation request is made and load a fixed error message into web view instead?

我的委托方法代码是

   func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    webView.stopLoading()
    webView.loadHTMLString(Constants.OfflineHtmlString!,baseURL:  nil)
}

推荐答案

如果需要在未连接互联网时向用户显示错误信息,

IF the need is to display error Info to the user when not connected to internet,

您甚至可以在加载请求之前检查您是否已连接到互联网;Reachability 是一个流行的 api,通常有助于检查这一点.这里似乎有一个快速端口https://github.com/ashleymills/Reachability.swift

You can check if you are connected to the internet even before loading the request; Reachability is a popular api that usually helps checking this. There seems to be a swift port of it here https://github.com/ashleymills/Reachability.swift

我建议采用上述选项;如果您仍然希望它失败然后显示错误,请确保 OfflineHtmlString 的正确性并在加载 OfflineHtmlString 之前验证错误代码;

I recommend to pursue the above option; In case you still want to allow it to fail and then display the error, Ensure the correctness of your OfflineHtmlString and verify the error code before loading the OfflineHtmlString;

我不知道你的html字符串是否有效;如果它是有效的,我会做类似下面的事情;

I don't know if your html string is valid; Provided it is valid, i would do something like below;

func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
   if(error.code == NSURLErrorNotConnectedToInternet){
       webView.loadHTMLString(Constants.OfflineHtmlString!,baseURL:  nil)
   }
}

这篇关于当 WKWebView loadRequest 失败时加载自定义错误 htmlString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆