先说明一下我的需求,这里是用wkwebview嵌套了一层h5的页面,在
h5页面做跳转时,会有可能地址加载404的情况,这个时候会显示白屏,然后我需要获取到加载页面结果的事件,取出状态码,如果是404的情况下给一个【点击刷新重试】的按钮。
找到拦截的方法
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
参数说明
webView:当前控制器(Controller类)WkWebView实例对象
navigationResponse:webView发生重定向后获取网页地址的返回结果,可以从中获取状态码等信息
decisionHandler:没用过,暂时不知道
获取状态码,判断状态
let response:HTTPURLResponse = navigationResponse.response as! HTTPURLResponse
if(response.statusCode == 404) {
self.view.addSubview(refreshLabel)
//这里貌似设置顶层的View的为false
refreshLabel.translatesAutoresizingMaskIntoConstraints = false
refreshLabel.backgroundColor = UIColor.init(white: 0.5, alpha: 0.3)
refreshLabel.layer.cornerRadius = 10
refreshLabel.clipsToBounds = true
refreshLabel.text = "加载失败,请重试"
refreshLabel.textAlignment = .center
refreshLabel.isUserInteractionEnabled = true refreshLabel.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(self.refreshCurrentUrl)))
let widthConstraint = NSLayoutConstraint(item: refreshLabel, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 150)
//设置约束条件
refreshLabel.addConstraint(widthConstraint)
//为控件添加约束
let heightConstraint = NSLayoutConstraint(item: refreshLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 30)
refreshLabel.addConstraint(heightConstraint)
let centerYConstraint = NSLayoutConstraint(item: refreshLabel, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1.0, constant: 0)
refreshLabel.superview!.addConstraint(centerYConstraint)
let centerXConstraint = NSLayoutConstraint(item: refreshLabel, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1.0, constant: 0)
refreshLabel.superview!.addConstraint(centerXConstraint)
}
decisionHandler(.allow)
这里获取了状态码,如果是404加入了【点击刷新重试】的Label,这里的代码是在网上找的,包括添加约束,设置背景等等。
refreshLabel.addGestureRecognizer这个方法还没测试,因为这个页面现在连加载都加载不出,直接进不去,我在外面通过导航失败的拦截方法直接拦截了。也正是因为现在测不了,我才有时间写这篇博客。
有问题可以评论区讨论哦~我是Java转ios半个月的小白,希望有大神指正我一些陋习和毛病!