How to update a Uiwebview to include and remove a Uiactivityindicatorview

Asked

Viewed 151 times

1

I am having difficulty including and finishing the display of a Uiactivityindicatorview ("loading animation"). I have tried using webViewDidStartLoad and webViewDidFinishLoad respectively to start and finish the animation, but I was unsuccessful. The code I’m using is this:

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var visaoWeb: UIWebView!
    @IBOutlet weak var carregamento: UIActivityIndicatorView!

    let urlString : String = "http://www.google.com"

    override func viewDidLoad() {

        if let url = NSURL(string: self.urlString) {
            let requestObj = NSURLRequest(url: url as URL)
            self.visaoWeb.loadRequest(requestObj as URLRequest)
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    func webViewDidStartLoad(_ webView: UIWebView) {
        self.carregamento.startAnimating()
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        self.carregamento.stopAnimating()
    }
     */

}

Note: I am using Swift 3.0

  • 1

    the correct Swift 3 would be if let url = URL(string: urlString) { visaoWeb.loadRequest(URLRequest(url: url)) }

  • 1

    Thank you @Leodabus, now I feel that the code is slowly evolving. A doubt, it would be appropriate to use self.variavel to refer to variables of the class itself?

1 answer

3


You are on the right track Fábio. There are some things that may be preventing your code from working properly.

  1. For the Uiwebview delegate methods to be called it is necessary to pass to the webView which object will be your delegate, in the self case. You can do this by the nib or in the code (self.visaoWeb.delegate = self)
  2. The code accesses a url with http link. By default App Transport Security will block this type of connection. Use https or add an exception to allow http access.
  3. Check the Storyboard to make sure the connection to the outlets is correct (view and loading)
  4. Use the correct method signature webViewDidFinishLoad

    func webViewDidFinishLoad(_ webView: UIWebView) {
    
      self.carregamento.stopAnimating()
      self.carregamento.removeFromSuperview()
    }
    
  • Thank you. I had to add the reference (self.visaoWeb.delegate = self) and correct the webViewDidFinishLoad signature. The rest was correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.