How to handle errors in WKWebview IOS Swift

-1

When we access a website without internet, does the browser return a certain error page? in my WKWebview I would like this to happen instead of appearing a white screen, how do I intercept this error?

    
asked by anonymous 01.10.2018 / 20:32

2 answers

1

This is an example implemented as a delegate method of the ViewController, which should be delegated from the WebView, ie in the viewDidLoad there should be something like a

html.navigationDelegate = self

The method that handles error follows:

func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
    NSLog("Erro de navegacao: \(error.localizedDescription)")
}
    
01.10.2018 / 21:27
0

You need to use 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

}
}
    
11.10.2018 / 21:13