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

参考: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后的参数。

下面看完整的:

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

你可能感兴趣的:(iOS与JS(二):MessageHandler(OC&Swift))