otter otter - 4 months ago 45
iOS Question

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?

Answer

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
Comments