swift开发技巧iOS开发记录iOS开发

ios开发加载webview显示进度条

2017-05-15  本文已影响221人  搬运工开发者

很多APP加载webView页面的时候都有进度条显示,今天我们这里主要使用相对轻量级的WKWebView加载网页,至于WKWebView 和UIWebView的区别与联系这里就不多讲了,自己百度哈哈。。。
WKWebView加载网页进度跳显示主要效果如下:

1.gif

这里主要是使用KVO监听WKWebView的“estimatedProgress”属性,通过监听该属性的变化才是进度条的长度。
1、定义便利构造函数、以及属性和控件

var url: String?
    var progresslayer = CALayer()
    var webView: WKWebView?
    var button: UIButton?
convenience init(title: String, url: String) {
        self.init()
        self.title = title
        self.url = url
    }

2、创建webview控件,并监听estimatedProgress,进度条初始化的时候会给一定的长度显示(原因下面解释)。

func setupUI() {
        webView = WKWebView(frame: CGRect.init(x: 0, y: 0, width: screenWidth, height: screenHeight-64.0))
        
        if url == "" {
            url = "http:www.baidu.com"
        }
        let request = URLRequest(url: URL(string: url ?? "http:www.baidu.com")!)
        webView?.load(request)
        webView?.uiDelegate = self
        webView?.navigationDelegate = self;
        view.addSubview(webView!)
        
        //添加属性监听
        webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        progresslayer.frame = CGRect.init(x: 0, y: 0, width: screenWidth * 0.1, height: 3)
        progresslayer.backgroundColor = UIColor.green.cgColor
        view.layer.addSublayer(progresslayer)
    }

3、监听estimatedProgress属性变化,并修改进度条长度,创建进度条的时候之所以给一定的默认长度主要是因为在没有网络的状态下会立即进度float == 1条件,这样给人的感觉就是没有加载网页一样。

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progresslayer.opacity = 1
            let float = (change?[NSKeyValueChangeKey.newKey] as! NSNumber).floatValue
            progresslayer.frame = CGRect.init(x: 0, y: 0, width: (screenWidth * CGFloat(float)) , height: 3)
            if float == 1 {
                weak var weakself = self
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: {
                    weakself?.progresslayer.opacity = 0
                })
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8, execute: {
                    weakself?.progresslayer.frame = CGRect.init(x: 0, y: 0, width: 0, height: 3);
                })
            }
        }else{
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }

4、web view加载失败后提示

extension KKWebView : WKUIDelegate, WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        guard let btn = button else {
            button = UIButton(type: .system)
            button?.frame = CGRect.init(x: 0, y: 3, width: screenWidth, height: screenHeight-64-3)
            button?.backgroundColor = UIColor.white
            button?.setTitleColor(UIColor.darkText, for: .normal)
            button?.setTitle("点击重新加载", for: .normal)
            button?.addTarget(self, action: #selector(loadURL), for: .touchUpInside)
            view.addSubview(button!)
            return
        }
        btn.isHidden = false
    }
}

5、记载失败后点击提示重新加载

 func loadURL() {
        button?.isHidden = true
        if url == "" {
            url = "http:www.baidu.com"
        }
        let request = URLRequest(url: URL(string: url ?? "http:www.baidu.com")!)
        webView?.load(request)
    }

5、移除监听,离开页面的时候需要移除KVO监听,否则会出现内存泄露

deinit {
        webView!.removeObserver(self, forKeyPath: "estimatedProgress")
    }
上一篇下一篇

猜你喜欢

热点阅读