Search code examples
iosswiftwebviewuiactivityindicatorview

Unable to start Activity Indicator in Swift 3?


I am new to IOS. I am trying to implement activity indicator while loading web view, but I am unable to do that.While debugging I encounter that animator is starting but it is not getting visible. I am using swift 3. Here my code is as below.Please let me know what I am doing wrong. If anyone have good resource to learn about activity indicator please mention that also.

class ViewController: UIViewController,UIWebViewDelegate {

   var WebView: UIWebView!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        WebView = UIWebView(frame: UIScreen.main.bounds)
        WebView.delegate = self
        view.addSubview(WebView)
        if let url = URL(string: "https://apple.com")
        {
            let request = URLRequest(url: url)
            WebView.loadRequest(request)
        }
        activityindicator.startAnimating()
        activityindicator.color = UIColor.black
        activityindicator.alpha = 1
        activityindicator.isHidden = false

    }

   // weak var activityindicator: UIActivityIndicatorView!
    let activityindicator = UIActivityIndicatorView()

    func webViewDidStartLoad(_ webView: UIWebView)
    {
        activityindicator.startAnimating()
        activityindicator.color = UIColor.black
        activityindicator.alpha = 1
        activityindicator.isHidden = false


        UIApplication.shared.isNetworkActivityIndicatorVisible = true
    }

    func webViewDidFinishLoad(_ webView: UIWebView)
    {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        activityindicator.stopAnimating()
        activityindicator.alpha = 0
        activityindicator.isHidden = true
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError)
    {
        activityindicator.isHidden = true
    }
}

Solution

  • Looks like the activity indicator is not added to view. Similar to how we are adding webview, center and add the indicator in viewDidLoad (code below).

    activityindicator.center = self.view.center view.addSubview(activityindicator)

    Also I would suggest moving the global declarations to one place. i.e move the indicator declaration let activityindicator = UIActivityIndicatorView(), to be below webview's on top, instead of middle of class. This helps in quick readability.