iOS Private APIs(1): Disabling Universal Links in WKWebView
2022-09-11
Disabling Universal Links in WKWebView
Universal Links provide a seamless user experience by allowing your web server to relate HTTP links to your website with corresponding links for your iOS app. However, there might be situations where you would like to disable this feature in a WKWebView
.
This guide will show you how to disable Universal Links from opening in-app and instead let them open in WKWebView
using Objective-C.
Prerequisites
- Xcode installed on your Mac.
- Basic knowledge of Objective-C.
- An existing iOS project with
WKWebView
set up.
Step-by-step Instructions
Step 1: Conform to the WKNavigationDelegate protocol
Your ViewController must conform to the WKNavigationDelegate
protocol. Declare this conformance in your interface declaration.
@interface YourViewController () <WKNavigationDelegate>
//...
@end
Step 2: Set WKWebView's navigationDelegate
Set your WKWebView instance's navigationDelegate property to self.
webView.navigationDelegate = self;
Step 3: Implement the decidePolicyForNavigationAction method
Implement the webView:decidePolicyForNavigationAction:decisionHandler:
delegate method. Here, we use WKNavigationActionPolicyAllow + 2
, which is a private API that handles Universal Links as normal web links.
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
decisionHandler((WKNavigationActionPolicy)(WKNavigationActionPolicyAllow + 2));
}
That's it! This will prevent your WKWebView
from opening Universal Links in-app.
Important Note
Using private APIs like WKNavigationActionPolicyAllow + 2
can lead to your app being rejected from the App Store. They're not documented or supported and may change or disappear without notice in future iOS versions. Use them cautiously and only when necessary. Always consider the potential risks and consequences before deciding to use private APIs in production code.
-EOF-