iosobjective-cwkwebviewurl-schemewkurlschemehandler

iOS - WKURLSchemeHandler not called on custom scheme


I want to use WKWebView and WKURLSchemeHandler to catch some links with custom schemes. To understand how it works, I've made a simple project (in Objective-C, sorry) with a local html file containing custom schemes

<html>

<h1>Local Links</h1>
<p><a href="./www/page.html">Local link</a></p>
<p><a href="./www/done.png">Local Image</a></p>

<h1>MyScheme Links</h1>
<p><a href="myscheme://www/page.html">Local link</a></p>
<p><a href="myscheme://www/done.png">Local Image</a></p>

</html>

In my ViewController, I initialize my webView as follow :

static NSString *const kCustomScheme = @"myscheme";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.webView.navigationDelegate = self;
    [self.webView.configuration setURLSchemeHandler:[MySchemeHandler new] forURLScheme:kCustomScheme];
}

Now, here is my custom SchemeHandler

#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>

@interface MySchemeHandler : NSObject<WKURLSchemeHandler>


@end
@interface MySchemeHandler () <WKURLSchemeHandler>

@end

@implementation MySchemeHandler

# pragma mark - WKURLSchemeHandler callbacks

- (void)webView:(nonnull WKWebView *)webView startURLSchemeTask:(nonnull id<WKURLSchemeTask>)urlSchemeTask {
    NSLog(@"startURLScheme");
    if ([urlSchemeTask.request.URL.absoluteString containsString:kCustomScheme]) {
        NSLog(@" --> scheme found");
    } else {
        NSLog(@" --> scheme not found");
    }
}

- (void)webView:(nonnull WKWebView *)webView stopURLSchemeTask:(nonnull id<WKURLSchemeTask>)urlSchemeTask {
    NSLog(@"stopURLScheme");
}

@end

With the above code, when I click on the custom link of my html page, nothing happens.

What am I doing wrong ? I can't see my mistake... I'm pretty new in Objective-C or, to be exact, I'm a bit rusty after 10 years of Android. So I would be happy if you could help me ;)


Solution

  • Finally, I've succeeded to catch my custom scheme.

    In fact, once the webView is created via IB, I'm not able to change its configuration. The only way to do this is to create the webView programmatically with the wanted configuration.

    Here is the resulting piece of code:

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    [config setURLSchemeHandler:[MySchemeHandler new] forURLScheme:kCustomScheme];
        
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
    self.webView.navigationDelegate = self;
    self.webView.allowsBackForwardNavigationGestures = YES;
        
    [self.view addSubview: self.webView];