Search code examples
iosswiftuiwebview

UIWebView offline error in Swift


I am loading a webpage into my app using UIWebView and following code:

let url = NSURL (string: "http://www.myurl.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);

I would like to hide webView if request failed for any reason, for example because of no access to internet. Is there a way to do it?


Solution

  • Use the provided delegate methods of UIWebView

    func webViewDidFinishLoad(webView: UIWebView) {
        print("webview did finish load!")
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        print("webview did fail load with error: \(error)")
    }
    

    Note: To use this method you need implement UIWebViewDelegate in your ViewController and set it with the webView outlet.

    myWebView.delegate = self