Skip to content

Instantly share code, notes, and snippets.

@joshbetz joshbetz/Webview.swift

Last active Aug 1, 2020
What would you like to do?
SwiftUI Webview with a Progress Bar
import SwiftUI
import WebKit
struct ContentView: View {
var body: some View {
Webview(url: URL(string: "")!)
struct Webview: UIViewControllerRepresentable {
let url: URL
func makeUIViewController(context: Context) -> WebviewController {
let webviewController = WebviewController()
let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
return webviewController
func updateUIViewController(_ webviewController: WebviewController, context: Context) {
let request = URLRequest(url: self.url, cachePolicy: .returnCacheDataElseLoad)
class WebviewController: UIViewController {
lazy var webview: WKWebView = WKWebView()
lazy var progressbar: UIProgressView = UIProgressView()
override func viewDidLoad() {
self.webview.frame = self.view.frame
self.progressbar.translatesAutoresizingMaskIntoConstraints = false
self.progressbar.topAnchor.constraint(equalTo: self.view.topAnchor),
self.progressbar.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
self.progressbar.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
self.progressbar.progress = 0.1
webview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
// MARK: - Web view progress
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
switch keyPath {
case "estimatedProgress":
if self.webview.estimatedProgress >= 1.0 {
UIView.animate(withDuration: 0.3, animations: { () in
self.progressbar.alpha = 0.0
}, completion: { finished in
self.progressbar.setProgress(0.0, animated: false)
} else {
self.progressbar.isHidden = false
self.progressbar.alpha = 1.0
progressbar.setProgress(Float(self.webview.estimatedProgress), animated: true)
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)

This comment has been minimized.

Copy link

OOXXXX commented May 22, 2020

Hi, your code is wonderful, but I have some problems when setting the constraints of the web view. Because on iPad, the web view will be scaled. Could you help me to solve the problem? Thanks
CleanShot 2020-0522 -0921@2x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.