iOS与JS(一):使用URL拦截的方式进行JS与OC互相调用

参考:

关于WKWebViewUIWebView之间的区别,本文就不在说明,本文只使用WKWebView
效果图如下:

html代码:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf8">
        <script language="javascript">
            function loadURL(url) {
                window.location.href = url
            }
            
            function locationClick() {
                loadURL("scheme://getLocation");
            }
            
            function shake() {
                loadURL("scheme://shake");
            }
            
            function setLocation(location) {
                alert(location)
                document.getElementById("returnValue").value = location;
            }
            
        </script>
    </head>
    
    <body>
        <h1>这是按钮调用</h1>
        <input type="button" value="获取定位" onclick="locationClick()" /><br><br>
        <input type="button" value="震动一下" onclick="shake()" /><br><br>
        
        <h1>这是文件上传</h1>
        <input type="file" /><br><br>
        
        <h1>这是回调结果展示区</h1>
        <textarea id ="returnValue" type="value" rows="5" cols="50"></textarea>
        
    </body>
</html>

以获取定位这个按钮为例说明OC和JS互相调用代码执行流程:

  1. 初始化WKWebView加载本地html文件。
  2. 点击web中的按钮,web发起URL请求。
  3. URL请求被WKNavigationDelegate中的代理方法拦截。根据自定义的URL识别使用不同的处理方式。如:在- (void)getLocation方法中调用JS的setLocation函数。
  4. JS的setLocation函数执行JS的alert()函数,被WKUIDelegate中的代理方法捕获,调用iOS原生的弹框。

详细代码说明

  • 初始化WKWebView加载本地html文件

      - (void)initWKWebView
      {
          // 1
          WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
          configuration.userContentController = [WKUserContentController new];
          WKPreferences *preferences = [WKPreferences new];
          preferences.javaScriptCanOpenWindowsAutomatically = YES;
          preferences.minimumFontSize = 40.0;
          configuration.preferences = preferences;
          
          self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
          
          // 2
          NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
          NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
          [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
          
          self.webView.navigationDelegate = self;
          self.webView.UIDelegate = self;
          [self.view addSubview:self.webView];
      }
    
    • 1 WKWebView的一些参数配置
    • 2 加载本html
  • URL请求被WKNavigationDelegate中的代理方法拦截。也就是JS调用了OC

      #pragma mark - WKNavigationDelegate
      - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
      {
          NSURL *URL = navigationAction.request.URL;
          NSString *scheme = [URL scheme];
          if ([scheme isEqualToString:@"scheme"]) {
              
              [self handleCustomAction:URL];
              
              decisionHandler(WKNavigationActionPolicyCancel);
              return;
          }
          decisionHandler(WKNavigationActionPolicyAllow);
      }
    
  • OC 调用 JS

      - (void)getLocation
      {
          // 将结果返回给js
          NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"上海市浦东新区"];
          [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
              NSLog(@"%@----%@",result, error);
          }];
      }
    
    • JS代码被当成字符串调用
    • completionHandler是JS代码被调用后回调
  • JS中alert弹窗被WKUIDelegate中的代理方法捕获,调用iOS原生的弹框。

      #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];
      }
    

最后,html中的文件input可以直接调用iOS的图片库,相机和文件。

代码: 90-iOSJS/OCJS1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 通过本篇文章,至少可以学习到: OC如何给JS注入对象及JS如何给IOS发送数据 JS调用alert、confir...
    一个叫小强的程序猿阅读 4,832评论 2 0
  • 随着H5技术的兴起,在iOS开发过程中,难免会遇到原生应用需要和H5页面交互的问题。其中会涉及方法调用及参数传值等...
    Chris_js阅读 8,272评论 1 8
  • 1、加载网页 WKWebView *webView = [[WKWebView alloc] initWithFr...
    LearningCoding阅读 8,334评论 0 2
  • 明明在北邮人上找了学姐内推,也收到邮件让我完善简历了,但后来还是发短信让我参加笔试,奇怪了,不管了,该走多少程序就...
    RAUL_AC阅读 5,378评论 2 8
  • 感恩万物 随时有感恩的心 平安喜悦吉祥 改变命运的方法: 忏悔,宽恕,祈祷,感恩 女儿的种种问题都是因为自己做得不够好
    Amy心灵之屋阅读 1,397评论 0 0