Using UIActivityIndicatorView with UIWebView in Swift

agwin27 picture agwin27 · Apr 2, 2015 · Viewed 19.6k times · Source

I'm trying to display an Activity Indicator View in my app to users while a url is being loaded into a WebView. I've tried toying with activity.startAnimating/activity.stopAnimating and tried placing them in functions, etc. but have not had any luck.

The best I have been able to get is the Activity Indicator to appear and animate, but then not stop animating or hide once my url is loaded, so it continues spinning on top of the web page.

In other situations, when trying to move around activity.startAnimating, I have encountered the "Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" issue. I have "Hides when Stopped" checked in the attributes inspector, I know that my url is valid, and I have created IBOutlets for the Interface Builder Elements.

Bear with me; I'm relatively new to Swift. Here's my code:

class HighchartsController: UIViewController {

@IBOutlet weak var HighchartsView: UIWebView!

@IBOutlet weak var activity: UIActivityIndicatorView!

@IBOutlet weak var saveButton: UIBarButtonItem!

@IBOutlet weak var highchartsMenu: UIBarButtonItem!

override func viewDidLoad()
{
    super.viewDidLoad()

    if self.revealViewController() != nil {
        highchartsMenu.target = self.revealViewController()
        highchartsMenu.action = "revealToggle:"

        loadAddress()
    }
 }

func loadAddress() {

    let url = NSURL (string: "http://google.com/flights")
    let request = NSURLRequest (URL: url!)
    HighchartsView.loadRequest(request)
    println("Webpage Loaded Successfully")
 }
}

And I have tried using different functions such as

webViewDidStartLoad(_ :UIWebView){

    activity.startAnimating()
    NSLog("Webview load has started")

}
webViewDidFinishLoad(_ :UIWebView){

    activity.stopAnimating()
    NSLog("Webview load had finished")

}

Answer

dimpiax picture dimpiax · Apr 2, 2015

First of all, i don't see delegation of UIWebView. Realize your behaviour related to delegation processes.

UIWebViewDelegate has four methods, but use for this way just three:

Swift 4

func webViewDidStartLoad(_ webView: UIWebView) // show indicator    
func webViewDidFinishLoad(_ webView: UIWebView) // hide indicator
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) // hide indicator

Swift 3

func webViewDidStartLoad(webView: UIWebView!) // show indicator
func webViewDidFinishLoad(webView: UIWebView!) // hide indicator
func webView(webView: UIWebView!, didFailLoadWithError error: NSError!) // hide indicator