How to detect and handle HTTP error codes in UIWebView?

前端 未结 9 796
无人及你
无人及你 2021-02-02 11:54

I want to inform user when HTTP error 404 etc is received. How can I detect that? I\'ve already tried to implement

- (void)webView:(UIWebView *)webView didFailL         


        
9条回答
  •  既然无缘
    2021-02-02 12:32

    I am new to iOS and Swift development, and needed to find a way to accomplish this as well, using WKWebView (not UI). I was fortunate enough to run across this site that gave me the following answer, which works perfectly for my needs. It might help passers-by that are looking for the same answer I was.

    Using this function (from WKNavigationDelegate):

    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
    

    You can create custom responses based on the HTTP response, like so:

    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    
        // get the statuscode
        guard let statusCode = (navigationResponse.response as? HTTPURLResponse)?.statusCode
        else {
            decisionHandler(.allow)
            return
        }
    
        // respond or pass-through however you like
        switch statusCode {
        case 400..<500:
            webView.loadHTMLString("

    You shall not pass!

    ", baseURL: nil) case 500..<600: webView.loadHTMLString("

    Sorry, our fault.

    ", baseURL: nil) default: print("all might be well") } decisionHandler(.allow) }

提交回复
热议问题