ios下OC与JS交互之WKWebView

2020-01-18 21:23:08王冬梅

2. WKUIDelegate

创建一个新的WKWebView


// 创建一个新的WebView

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures; 

剩下三个代理方法全都是与界面弹出提示框相关的,针对于web界面的三种提示框(警告框、确认框、输入框)分别对应三种代理方法。


// 界面弹出警告框

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(void (^)())completionHandler;

// 界面弹出确认框

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;

// 界面弹出输入框

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler; 

3. WKScriptMessageHandler

这个协议中包含一个必须实现的方法,这个方法是native与web端交互的关键,它可以直接将接收到的JS脚本转为OC或Swift对象。


// 从web界面中接收到一个脚本时调用

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message; 

三、使用WKWebView重写

这里我们和之前的界面做了一点改动,之前OC调用JS的时候是进行弹框处理,这里我在写的时候,很郁闷,方法可以调用过去,但是唯独js的alert方法调用没有效果,所以这里采用了输出到div的形式,并增加了一个clear按钮

WKWebView不支持nib文件,所以这里需要使用代码初始化并加载WebView


WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

config.preferences.minimumFontSize = 18;

 

self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height/2) configuration:config];

[self.view addSubview:self.wkWebView];

 

 

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];

NSURL *baseURL = [[NSBundle mainBundle] bundleURL];

[self.wkWebView loadHTMLString:[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil] baseURL:baseURL]; 

OC端:


//1. JS调用OC 添加处理脚本

[userCC addScriptMessageHandler:self name:@"showMobile"];

[userCC addScriptMessageHandler:self name:@"showName"];

[userCC addScriptMessageHandler:self name:@"showSendMsg"];

 

// 在代理方法中处理对应事件

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {

  NSLog(@"%@",NSStringFromSelector(_cmd));

  NSLog(@"%@",message.body);

 

  if ([message.name isEqualToString:@"showMobile"]) {

    [self showMsg:@"我是下面的小红 手机号是:18870707070"];

  }

   

  if ([message.name isEqualToString:@"showName"]) {

    NSString *info = [NSString stringWithFormat:@"你好 %@, 很高兴见到你",message.body];

    [self showMsg:info];

  }

   

  if ([message.name isEqualToString:@"showSendMsg"]) {

    NSArray *array = message.body;

    NSString *info = [NSString stringWithFormat:@"这是我的手机号: %@, %@ !!",array.firstObject,array.lastObject];

    [self showMsg:info];

  }

}

 

// 2. native调用js

- (IBAction)btnClick:(UIButton *)sender {

  if (!self.wkWebView.loading) {

    if (sender.tag == 123) {

      [self.wkWebView evaluateJavaScript:@"alertMobile()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {

        //TODO

        NSLog(@"%@ %@",response,error);

      }];

    }

     

    if (sender.tag == 234) {

      [self.wkWebView evaluateJavaScript:@"alertName('小红')" completionHandler:nil];

    }

     

    if (sender.tag == 345) {

      [self.wkWebView evaluateJavaScript:@"alertSendMsg('18870707070','周末爬山真是件愉快的事情')" completionHandler:nil];

    }

 

  } else {

    NSLog(@"the view is currently loading content");

  }

}