Intercepting UIWebView & WKWebView — Custom URL Scheme handling
Before we get into the details, lets first see the problem statement.
Problem Statement
How should we provide an option for the user to upload a photo from the phone into the WebView?
Solution :
use NSURLProtocol & UIWebView for iOS9 & iOS10, use WKSchemeHandler & WKWebView for iOS11. Okay lets deep dive into the details.
WKWebview was introduced in iOS 8, and it is recommended to use WKWebView instead of UIWebView.
ImportantStarting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView.
Till iOS 11, we do not have any system APIs to intercept events from WKWebView.In iOS 11 we got a new API called WKURLSchemeHandler for WKWebView to make our life simpler.
WKSchemeHandlerprotocol for loading resources with URL schemes that WebKit doesn't know how to handle.
It means that if you want to handle some request on your own, then just define the custom scheme and set it to the WKWebViewConfiguration.
created a class called CustomeSchemeHandler
which will be implementing WKURLSchemeHandler
methods to handle the interceptors. Finally, we are setting it to the WKWebViewConfiguration.
we are saying to the WebKit that whenever you see a scheme "custom-scheme://",please don't handle this request. Just send the request back to CustomSchemeHandler to handle.
Whenever WKWebView finds the custom-scheme
while loading, the request will be sent to the scheme handler to handle the request. It is an asynchronous request. Every request is going to be handed to us in the form of WKURLSchemeTask
. Post success sends the response, data and then call finish on the task.
To handle the same for UIWebView, we need to provide a class which implements URLProtocol
and register the class in didfinishLaunchWithOptions.
You can find the project here.
You can check out the other articles as well.