IOS Swift5 WkWebView 跳转网页后 加载页面结果方法拦截(WKNavigationResponse)

先说明一下我的需求,这里是用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半个月的小白,希望有大神指正我一些陋习和毛病!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值