How to handle errors in Wkwebview IOS Swift

Asked

Viewed 80 times

-1

When we access a website without internet the browser returns an error page right? in my Wkwebview I would like it to happen instead of appearing a white screen, as I intercept this error?

2 answers

1

Here is an example implemented as a delegated Viewcontroller method, which should be delegated to Webview, i.e., in viewDidLoad there should be something like a

html.navigationDelegate = self

Follows the method that treats error:

func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    NSLog("Erro de navegacao: \(error.localizedDescription)")
}
  • I had found this alternative but it takes a long time to trigger the error, example is taking about 15s to appear the error, has to decrease to an accessible time ?

0

You need to use the Reachability

import UIKit
import WebKit
import SystemConfiguration

class ViewController: UIViewController {

@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    if Reachability.isConnectedToNetwork() {
        if let url = URL(string: "www.google.com") {
            webView.load(URLRequest(url: url))
            webView.allowsBackForwardNavigationGestures = true
            webView.navigationDelegate = self
        }
    }else {
        print("sem conexao")
    }
}
}

extension ViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
     print(error.localizedDescription)
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
     print("Webview is loading")
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("")
}
}

public class Reachability {

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    let ret = (isReachable && !needsConnection)

    return ret

}
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.