Search code examples
iosobjective-ciphoneswiftwkwebview

How to check if Link is broken with WKWebview?


I use WKWebview to load a URL.

let webView = WKWebview()
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url!)
webView.loadRequest(request)

How can I detect if the link the webView should load is broken?


Solution

  • You can use canOpenUrl method:

    UIApplication.sharedApplication().canOpenURL(url)
    

    It will do the url validation and if the link is ok it returns true. It's mostly use before you call:

    UIApplication.sharedApplication().openURL(url) 
    

    to make sure this link can be open in safari but it should help you here too.

    Make sure the link starts with http:// or https://.

    Edited:

    It will just check is the link is a correct url.

    If you want to see the page is offline, authorisation issues, etc. you can implement WKNavigationDelegate protocol and check out this method:

    - webView:didFailNavigation:withError:
    

    this should give you more info.

    It's always good idea to use: str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAl‌​lowedCharacterSet())! it make sure that you don't pass a character which are not allowed in URL.

    Edited 2: To detect the status code you can try to implement:

    - webView:decidePolicyForNavigationResponse:decisionHandler:
    

    the navigation response is an NSURLResponse instance but whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class so you should cast it to NSHTTPURLResponse. That should give you a statusCode. In the last line in the method you should call handler, for example decisionHandler(WKNavigationResponsePolicyAllow).