How to add Activity Indicator to WKWebView (Swift 3)
Asked Answered
I

6

25

I have a wkwebview in my app, and I want to add an activity indicator to it. I want it to where it appears when the webview is loading and disappears whenever it is finished loading, it disappears. Can you give me some code to do this? Here's my code right now:

@IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!


@IBOutlet var containerView: UIView? = nil


override func viewDidLoad() {
    super.viewDidLoad()

    guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }

    webView = WKWebView(frame: self.view.frame)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.isUserInteractionEnabled = true
    webView.navigationDelegate = self

    self.view.addSubview(self.webView)

    let request = URLRequest(url: url)
    webView.load(request)

}


func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

    // Check if a link was clicked
    if navigationAction.navigationType == .linkActivated {

        // Verify the url
        guard let url = navigationAction.request.url else { return }
        let shared = UIApplication.shared

        // Check if opening in Safari is allowd
        if shared.canOpenURL(url) {

            // Ask the user if they would like to open link in Safari
            let alert = UIAlertController(title: "Do you want to open Safari?", message: nil, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert: UIAlertAction) -> Void in
                // User wants to open in Safari
                shared.open(url, options: [:], completionHandler: nil)
            }))
            alert.addAction(UIAlertAction(title: "Opps, no.", style: .cancel, handler: nil))

            present(alert, animated: true, completion: nil)

        }
        decisionHandler(.cancel)
    }
    decisionHandler(.allow)
}

func webViewDidStartLoad(_ : WKWebView) {
    Activity.startAnimating()
}

func webViewDidFinishLoad(_ : WKWebView) {
    Activity.startAnimating()
}

I'm creating an IOS app using xcode 8 and swift 3

Inchoation answered 26/11, 2016 at 14:59 Comment(3)
What is your problem?Liebowitz
I need help adding an Activity Indicator to my WKWebView I want it to where it appears when the webview is loading and disappears whenever it is finished loading, it disappears. Can you give me some code to do this?Inchoation
Possible duplicate of Displaying activity indicator on WKWebView using swiftYttria
T
46

Please, below code which is working fine.

@IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!
@IBOutlet var containerView: UIView? = nil

override func viewDidLoad() {
    super.viewDidLoad()
    
    guard let url = URL(string: "http://www.facebook.com") else { return }
    webView = WKWebView(frame: self.view.frame)
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.isUserInteractionEnabled = true
    self.view.addSubview(self.webView)
    let request = URLRequest(url: url)
    webView.load(request)
    
    // add activity
    self.webView.addSubview(self.Activity)
    self.Activity.startAnimating()
    self.webView.navigationDelegate = self
    self.Activity.hidesWhenStopped = true
    
}

Implement below these two delegate method:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    Activity.stopAnimating()
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    Activity.stopAnimating()
}

Let me know if it is not working.

Tremolant answered 27/11, 2016 at 17:56 Comment(4)
The activity indicator is working, but the web view content is not loading.Inchoation
can u share the url ?Tremolant
This solution is just what I needed but I'm curious @Sandy: why do I have to add an ActivityIndicator as a subview to the WKWebView instead of adding it as a top subview to the main view (using bringSubview(toFront:) method). I'm not an expert by any means but at first glance it looks like both solutions should workBerlin
Why was webView.navigationDelegate = self added twice?Sevenfold
N
31
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

    var webView: WKWebView!
    var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        webView = WKWebView(frame: CGRect.zero)
        webView.navigationDelegate = self
        webView.uiDelegate = self

        view.addSubview(webView)

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray

        view.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)
    }
}
Neoteric answered 31/5, 2018 at 6:5 Comment(2)
This is more correct approach, as it handles navigation between pages of the WKWebViewViolone
WKUIDelegate is not required. The delegate methods given in the example are from WKNavigationDelegate.Achieve
A
5

In viewDidLoad you need to add the activityIndicator as a subView just as you did for your webView. Since it's an outlet, make sure the activityIndicator sits on top of your webView and you should be good to go. You also want to set activity.hidden to true when the webView stops loading.

It's also a good rule of thumb to lower case your 'Activity' outlet.

override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.Activity)

guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }

webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
webView.navigationDelegate = self

self.view.addSubview(self.webView)


let request = URLRequest(url: url)
webView.load(request)

You also call activity.startAnimating in webViewDidFinishLoad(). Make sure you call activity.stopAnimating() when the webView finishes loading. Happy coding!

    func webViewDidFinishLoad(_ : WKWebView) {
    Activity.stopAnimating()
    Activity.hidden = true
}
Aret answered 27/11, 2016 at 17:3 Comment(1)
This was the only version which worked for me. With the check marked version, my web page did not display when I centered the activity indicator horizontal/vertical. This worked as desired.Crosshead
P
5

Swift 5 Version

The concept is simple enough to be ported to earlier swift versions.

This is a class we would use as a parent class anywhere we want a webview.

import UIKit
import WebKit

class CustomWebViewController: UIViewController, WKNavigationDelegate {
    var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        activityIndicator = UIActivityIndicatorView()
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.style = .gray
        activityIndicator.isHidden = true

        view.addSubview(activityIndicator)
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        activityIndicator.isHidden = false
        activityIndicator.startAnimating()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndicator.stopAnimating()
        activityIndicator.isHidden = true
    }
}

If we have a UIViewController with a webview, we can just inherit from CustomWebViewController and it will take care of the rest for us. Remember to connect the webview IBOutlet.

import UIKit
import WebKit

class FirstViewController: CustomWebViewController {

    @IBOutlet var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.navigationDelegate = self

        let url = URL(string: "https://google.com")
        webView.load(URLRequest(url: url!))
    }
}
Poundfoolish answered 30/9, 2019 at 0:43 Comment(0)
A
0
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
    webView = WKWebView(frame: CGRect.zero)
    webView.navigationDelegate = self;
    webView.uiDelegate = self


    activityIndicator = UIActivityIndicatorView()
    activityIndicator.hidesWhenStopped = true
    activityIndicator.center = self.view.center
    activityIndicator.style = UIActivityIndicatorView.Style.large

    webView.addSubview(activityIndicator)
    view = webView

    let load_url = URL(string: "https://google.com/")!
    webView.load(URLRequest(url: load_url))
    activityIndicator.startAnimating()

    let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
    toolbarItems = [refresh]
    navigationController?.isToolbarHidden = false
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    title = webView.title
    activityIndicator.stopAnimating()
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    activityIndicator.startAnimating()
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    activityIndicator.stopAnimating()
}
}
Amyotonia answered 10/12, 2019 at 10:57 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Hernandes
G
0

Please try the below code its working fine for me and please let me know if anything is wrong in it thanks in advance.

import UIKit
import WebKit

class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

@IBOutlet weak var contentView: UIView!
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()

    setupView()
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    self.setupWebView()
    self.loadData()
}

fileprivate func setupView() {

    self.contentView.isHidden = true
    self.activityIndicatorView.startAnimating()
}

fileprivate func setupWebView() {

    let webConfiguration = WKWebViewConfiguration()

    webView = WKWebView(frame: contentView.bounds, configuration: webConfiguration)
    webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.contentView.addSubview(webView)
    self.webView.allowsBackForwardNavigationGestures = true
    webView.uiDelegate = self
    webView.navigationDelegate = self
}

fileprivate func loadData() {

    if let url = URL(string: "http://google.com") {

        /// For loading PDF content 
        if contentType == .pdf {

              if let data = try? Data(contentsOf: url) {
                   self.webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: url)
              }
        } else {

           let request = URLRequest(url: url)
           webView.load(request)
        }  
   }
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    activityIndicatorView.stopAnimating()
    self.contentView.isHidden = false
}

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    activityIndicatorView.stopAnimating()
}
}
Gona answered 30/12, 2019 at 12:20 Comment(1)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Hernandes

© 2022 - 2024 — McMap. All rights reserved.