Skip to content

Instantly share code, notes, and snippets.

@david-hosier
Last active October 31, 2023 04:15
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save david-hosier/aa2ccf05553d3e1137c24775259e094f to your computer and use it in GitHub Desktop.
Save david-hosier/aa2ccf05553d3e1137c24775259e094f to your computer and use it in GitHub Desktop.
Shows a ViewController that contains a WKWebView and UIActivityIndicatorView. This is a pruned down snippet from working code that may or may not work exactly as-is, but should give the basic idea of how to show/hide an activity indicator while a WKWebView is navigating to a URL. The original project this was adapted from was done in XCode 8, an…
import Foundation
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
@IBOutlet var webViewContainer: UIView!
override func viewDidLoad() {
webView = WKWebView(frame: CGRect.zero)
webView.navigationDelegate = self
webView.uiDelegate = self
webViewContainer.addSubview(webView)
activityIndicator = UIActivityIndicatorView()
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
webViewContainer.addSubview(activityIndicator)
webView.load(URLRequest(url: URL(string: "http://google.com")!))
}
func showActivityIndicator(show: Bool) {
if show {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
showActivityIndicator(show: true)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
showActivityIndicator(show: false)
}
}
@enzosterro
Copy link

But at viewDidLoad() self.view.center is (0, 0), isn't it?

@freetonik
Copy link

Line 21: A few things got renames, now it's

activityIndicator.style = UIActivityIndicatorView.Style.gray

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment