iOS与JS(二):MessageHandler(OC&Swift)

2017-09-07 stivenJemm

参考: iOS下JS与OC互相调用(三)–MessageHandler

iOS与JS的相互调用除了URL拦截( iOS与JS(一):使用URL拦截的方式进行JS与OC互相调用 )外,还可以使用 WKWebView 的中的MessageHandler来实现。

MessageHandler是什么呢?以代码来说明,比较好理解。

在OC中初始化 WKWebView 是,添加如下代码:

[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];

那么在JS中就可以使用:

window.webkit.messageHandlers.Location.postMessage(null);

JS中的 Location 就对应OC中的 namepostMessage 后的参数就是JS传给OC的参数,类型可以是 NSNumber, NSString, NSDate, NSArray, NSDictionary, and NSNull。

JS回调OC时,就回调 WKScriptMessageHandler- (void)userContentController:([WKUserContentController](apple-reference-documentation://hcracoR5p2) *)userContentController didReceiveScriptMessage:([WKScriptMessage](apple-reference-documentation://hcD3KQdcJY) *)message; 方法,这边的 messageWKScriptMessagemessage.name 就是“Location”, message.body 就是 postMessage 后的参数。

下面看完整的:chestnut::

html的代码

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf8">
            <script language="javascript">
            var ctuapp_share_img="www.baidu.com";

            function locationClick() {
                window.webkit.messageHandlers.Location.postMessage(null);
            }
            
            function shake() {
                window.webkit.messageHandlers.Shake.postMessage(null);
            }
            
            function payClick(){
            window.webkit.messageHandlers.Pay.postMessage({order_no:'201511120981234',channel:'wx',amount:1,subject:'粉色外套'});
            }
            
            function setLocation(location) {
                alert(location)
                document.getElementById("returnValue").value = location;
            }
            
            function payResult(str) {
                alert(str);
                document.getElementById("returnValue").value = str;
            }
            
                </script>
            </head>
    
    <body>
        <h1>这是按钮调用</h1>
        <input type="button" value="获取定位" onclick="locationClick()" /><br><br>
        <input type="button" value="震动一下" onclick="shake()" /><br><br>
        <input type="button" value="支付" onclick="payClick()" /><br><br>

        
        <h1>这是文件上传</h1>
        <input type="file" /><br><br>
        
        <h1>这是回调结果展示区</h1>
        <textarea id ="returnValue" type="value" rows="5" cols="50"></textarea>
        
    </body>
</html>

初始化WKWebView

- (void)initWKWebView
{
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 40.0;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
    
    
    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
}

添加 MessageHandler

为了防止循环引用,结束时释放。

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // addScriptMessageHandler 很容易导致循环引用
    // 控制器 强引用了WKWebView,WKWebView copy(强引用了)configuration, configuration copy (强引用了)userContentController
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Shake"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Pay"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Shake"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Pay"];
}

实现WKUIDelegate和WKScriptMessageHandler协议方法

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //    message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    NSLog(@"body:%@",message.body);
    if ([message.name isEqualToString:@"Location"]) {
        [self getLocation];
    } else if ([message.name isEqualToString:@"Shake"]) {
        [self shakeAction];
    } else if ([message.name isEqualToString:@"Pay"]) {
        [self payWithParams:message.body];
    }
}

效果:

Swift的和OC类型,代码我也一起写了

代码: 90-iOSJS 中的 OCJSMessageHandlerSwiftJSMessageHandler

本文作者:AndyRon


用户评论
开源开发学习小组列表