Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active July 2, 2018 19:34
Show Gist options
  • Save KentarouKanno/b80e6c444cc56ab4622aee3e555eddd0 to your computer and use it in GitHub Desktop.
Save KentarouKanno/b80e6c444cc56ab4622aee3e555eddd0 to your computer and use it in GitHub Desktop.

WKWebView Progress(Swift4)

参考URL: Swift4のKVOに感動した。

// MARK: - WebView Progress

private var progressView = UIProgressView()
private var observers: [NSKeyValueObservation] = []

private func setUpProgress() {
    
    // NavigationBar下のプログレスバーを生成
    let progressHeight: CGFloat = 2.0
    let navigationHeight: CGFloat = navigationController?.navigationBar.frame.size.height ?? 46.0
    progressView = UIProgressView(frame: CGRect(x: 0.0,
                                                y: navigationHeight - progressHeight,
                                                width: view.bounds.width,
                                                height: progressHeight))
    progressView.progressViewStyle = .bar
    navigationController?.navigationBar.addSubview(self.progressView)
    observeKeysFowWebView()
}

private func observeKeysFowWebView() {
    
    observers.append(webview.observe(\.loading) { (wkWebView, _) in
        UIApplication.shared.isNetworkActivityIndicatorVisible = wkWebView.isLoading
        let value: Float = wkWebView.isLoading ? 0.1/* プログレスの開始 */ : 1.0 /* プログレスを消去 */
        self.progressView.setProgress(value, animated: true)
    })
    
    observers.append(webview.observe(\.estimatedProgress, options: .new) { (wkWebView, _) in
        self.progressView.setProgress(Float(wkWebView.estimatedProgress), animated: true)
    })
}

private func removeObserve() {
    observers.forEach { $0.invalidate() }
    observers.removeAll()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment