WKWebview - Failed to load resource: The request timed out

Viewed 505

Hello I have WkWebview app which load webpage here is my initialization code for wkwebview

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true
    preferences.setValue(true, forKey: "DeveloperExtrasEnabled")
    webConfiguration.preferences = preferences
    browser = WKWebView(frame: .zero, configuration: webConfiguration)
            browser.navigationDelegate = self
    browser.uiDelegate = self
    view = browser
}

and here is request

let url = URL(string: urlString)
    request = URLRequest(url: url!,cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,timeoutInterval: 360)
    browser.navigationDelegate = self
    browser.uiDelegate = self
    browser.load(request)

This works fine but when I click on subpage which load's more that 60s(which is default request timeout interval). I get this error in web-inspector Failed to load resource: The request timed out So my question is. Can I change default timeoutInterval for all requests?

PS: I did try to override navigationDelegate method.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { }

block the connection and load the subpage with new request but it didn't work.

PS: in Safari the subpage loads as expected only in WKWebview doesn't work.

Thank you for your answers or suggestions

1 Answers

You need to handle the case when webView(_:decidePolicyFor:decisionHandler:) function gets called the second time. (from your modified URLRequest with the new timeoutInterval)

Something like that will work:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    if navigationAction.request.timeoutInterval != 360 {
        var urlRequest = navigationAction.request
        urlRequest.timeoutInterval = 360
        decisionHandler(.cancel)
        webView.load(urlRequest)
    } else {
        decisionHandler(.allow)
    }
}
Related