Objective-C与JS交互 —— MessageHandler

addScriptMessageHandler很容易导致循环引用,控制器强引用了WKWebView,WKWebView copy(强引用了)configuration,configuration copy(强引用了)userContentController

  • 1.初始化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];
    
    // 注册
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"getLocation"];
}
  • 2.WKScriptMessageHandler注册Native方法
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"getLocation"]) {
        [self getLocation];
    }
}

#pragma mark - private method

- (void)getLocation {
    // 获取位置信息
    ···
    
    // 将结果返回给js
    NSString *locationStr = [NSString stringWithFormat:@"setLocation('%@')",@"广东省深圳市南山区学府路XXXX号"];
    [self.webView evaluateJavaScript:locationStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];

    1. JS调用OC
  function locationClick() {
     window.webkit.messageHandlers.getLocation.postMessage(null);
  }

你可能感兴趣的:(Objective-C与JS交互 —— MessageHandler)