DEV Community

Alastair Coote
Alastair Coote

Posted on

5

Getting WKWebView to treat a WKURLSchemeHandler as secure

The bad news upfront: you can't do this in an app you're going to submit to the App Store because it involves using a private API. But I thought it was interesting nonetheless.

In short: iOS's webview, WKWebView, allows you create a "custom scheme" and route all requests for it through your native code. So, for example, you could create resources:// and any request sent to a URL within that scheme would be answered by your app. The big problem is that WKWebView does not consider this scheme "secure", which means if you load an https:// URL it can't send requests to resources://, just like it can't send a request to http://.

But you can change that. There's a private method on WKProcessPool named _registerURLSchemeAsSecure and it does... well, more or less what the name would lead you to believe. So how to use it? Surprisingly simply:

let pool = WKProcessPool()
let selector = NSSelectorFromString("_registerURLSchemeAsSecure:")
pool.perform(selector, with: NSString(string: "resources"))
Enter fullscreen mode Exit fullscreen mode

Then just make your WKWebViewConfiguration has its processPool property set.

Ta-da! Now resources:// is secure and you can send requests from https:// URLs. So why doesn't Apple do this themselves internally? I suspect it has something to do with this being set at the WKProcessPool level: you add custom schemes per webview so it's possible for two webviews sharing the same process pool to have different custom schemes. Anyway, fingers crossed in a future release they'll be able to do the refactoring necessary to let us make custom schemes secure.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay