WKWebView intercepting Https URL

I'm developing an application that utilizes WKWebView to display a webpage. My goal is to improve the performance and loading speed of this webpage by intercepting specific API calls and providing pre-stored JSON responses directly from within the app, ensuring the webpage renders instantaneously.

The challenge I am encountering is the inability to intercept HTTPS URL schemes directly from WKWebView. Any insights or solutions from the community on how to effectively manage and overwrite these particular network requests would be greatly appreciated.

One option would be to use custom URL schemes to trigger your WKURLSchemeHandler, then load local or remote data depending on your logic.

If you define types such as:

enum LocalObjectType: String {
    case html = "html"
    case css = "css"
    case javascript = "javascript"
    case png = "png"
    case https = "https"
    case pdf = "pdf"
}

And reference it in your HTML

<html>
<head>
    <link rel="stylesheet" href="apple-localloader:css">
</head>
<body>
    <h1>Your content is all here </h1>
    <br>
    <img src="apple-localloader:png"/>
    <br>
    <img src="apple-localloader:https"/>

You can get a callback in

func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {

and handle it like this:

 else if type == LocalObjectType.png.rawValue {
            if let resource = Bundle.main.url(forResource: "image", withExtension: "png"),
               let resourceData = try? Data(contentsOf: resource) {
                data = resourceData
                response = URLResponse(
                    url: url,
                    mimeType: "image/png",
                    expectedContentLength: data!.count,
                    textEncodingName: nil)
            }
        } else if type == LocalObjectType.https.rawValue {
            if let resource = URL(string: "https://pngimg.com/uploads/frisbee/frisbee_PNG21.png"),
               let resourceData = try? Data(contentsOf: resource) {
                data = resourceData
                response = URLResponse(
                    url: url,
                    mimeType: "image/png",
                    expectedContentLength: data!.count,
                    textEncodingName: nil)
            }

Hopefully this helps.

Rico | WWDR | Software Engineer

WKWebView intercepting Https URL
 
 
Q