swift -WKWebView的加载进度和标题的观察者

这是一个WKWebView的进度观察者
private lazy var progressObservation: NSKeyValueObservation = {
    var observation = self.webView.observe(\.estimatedProgress, options: [.old, .new], changeHandler: { webView, change in
        self.progressCount += 1
        self.checkTimeout(self.progressCount, timeout: 10.0)
        if webView.estimatedProgress > 0.1 {
            self.progressView.setProgress(Float(webView.estimatedProgress), animated: true)
        }
        log.debug("网页\(self.urlString)加载进度为:\(self.webView.estimatedProgress),是否还在加载\(webView.isLoading)旧的进度为:\(change.oldValue ?? 0)新的进度为:\(change.newValue ?? 0)")
        if webView.estimatedProgress >= 1 {
            UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                
            }, completion: { (finish) in
                self.resetProgress()
            })
        }
    })
    return observation
}()

private func checkTimeout(_ count: Int, timeout: CGFloat) {
    Timer.after(10.second) {
        if count == self.progressCount {
            self.resetProgress()
            log.debug("\(timeout)秒进度没有动了,已经超时了,自动隐藏进度条")
            return
        }
    }
}

private func resetProgress() {
    self.progressView.isHidden = true
    self.progressView.setProgress(0.1, animated: false)
    self.progressCount = 0
}
这是WKWebView的标题观察者
private lazy var titleObservation: NSKeyValueObservation = {
    var observation = self.webView.observe(\.title, options: [.old, .new], changeHandler: { [weak self] webView, change in
        guard let `self` = self else { return }
        self.title = self.webView.title!.count > 0 ? self.webView.title : self.titleString
    })
    return observation
}()

你可能感兴趣的:(swift -WKWebView的加载进度和标题的观察者)