zoukankan      html  css  js  c++  java
  • JS与OC相互调用的基本使用

    JS调用原生OC篇

    方式一

    第一种方式是用JS发起一个假的URL请求,然后利用UIWebView的代理方法拦截这次请求,然后再做相应的处理。
    我写了一个简单的HTML网页和一个btn点击事件用来与原生OC交互,HTML代码如下:

    <html>
        <header>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
                function showAlert(message){
                    alert(message);
                }
    
                function loadURL(url) {
                    var iFrame;
                    iFrame = document.createElement("iframe");
                    iFrame.setAttribute("src", url);
                    iFrame.setAttribute("style", "display:none;");
                    iFrame.setAttribute("height", "0px");
                    iFrame.setAttribute("width", "0px");
                    iFrame.setAttribute("frameborder", "0");
                    document.body.appendChild(iFrame);
                    // 发起请求后这个 iFrame 就没用了,所以把它从 dom 上移除掉
                    iFrame.parentNode.removeChild(iFrame);
                    iFrame = null;
                }
                function firstClick() {
                    loadURL("firstClick://shareClick?title=分享的标题&content=分享的内容&url=链接地址&imagePath=图片地址");
                }
            </script>
        </header>
    
        <body>
            <h2> 这里是第一种方式 </h2>
            <br/>
            <br/>
            <button type="button" onclick="firstClick()">Click Me!</button>
    
        </body>
    </html>

    然后在项目的控制器中实现UIWebView的代理方法:

    #pragma mark - UIWebViewDelegate
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        NSURL * url = [request URL];
       if ([[url scheme] isEqualToString:@"firstclick"]) {
            NSArray *params =[url.query componentsSeparatedByString:@"&"];
    
            NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
            for (NSString *paramStr in params) {
                NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
                if (dicArray.count > 1) {
                    NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    [tempDic setObject:decodeValue forKey:dicArray[0]];
                }
            }
           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式一" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
           [alertView show];
           NSLog(@"tempDic:%@",tempDic);
            return NO;
        }
    
        return YES;
    }

    注意:1. JS中的firstClick,在拦截到的url scheme全都被转化为小写。
    2.html中需要设置编码,否则中文参数可能会出现编码问题。
    3.JS用打开一个iFrame的方式替代直接用document.location的方式,以避免多次请求,被替换覆盖的问题。

     

    方式二

    在iOS 7之后,apple添加了一个新的库JavaScriptCore,用来做UIWebView与JS交互,因此JS与原生OC交互也变得简单了许多。

    具体参照UIWebView之JavaScriptCore文章篇

     

    方式三

    使用WKWebView OC与JS交互

    具体参照WKWebView之MessageHandler篇的使用

    OC调用JS篇

    方式一

    NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"这里是JS中alert弹出的message"];
    [_webView stringByEvaluatingJavaScriptFromString:jsStr];

    注意:该方法会同步返回一个字符串,因此是一个同步方法,可能会阻塞UI。

    方式二

    继续使用JavaScriptCore库来做JS交互。

    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSString *textJS = @"showAlert('这里是JS中alert弹出的message')";
    [context evaluateScript:textJS];
    重点:
    stringByEvaluatingJavaScriptFromString是一个同步的方法,使用它执行JS方法时,如果JS 方法比较耗的时候,会造成界面卡顿。尤其是js 弹出alert 的时候。
    alert 也会阻塞界面,等待用户响应,而stringByEvaluatingJavaScriptFromString又会等待js执行完毕返回。这就造成了死锁。
    官方推荐使用WKWebViewevaluateJavaScript:completionHandler:代替这个方法。
    其实我们也有另外一种方式,自定义一个延迟执行alert 的方法来防止阻塞,然后我们调用自定义的alert 方法。同理,耗时较长的js 方法也可以放到setTimeout 中。
    function asyncAlert(content) {
        setTimeout(function(){
             alert(content);
             },1);
    }
  • 相关阅读:
    mvp在flutter中的应用
    Flutter 网络请求库http
    Flutter Dart中的异步
    阿里云 RDS 数据库又发 CPU 近 100% 的“芯脏病”团队
    上周热点回顾(10.14-10.20) 团队
    云上的芯脏病:奇怪的阿里云 RDS 数据库突发 CPU 近 100% 问题团队
    【故障公告】docker swarm 集群问题引发的故障团队
    上周热点回顾(10.7-10.13)团队
    上周热点回顾(9.30-10.6) 团队
    上周热点回顾(9.23-9.29) 团队
  • 原文地址:https://www.cnblogs.com/HJiang/p/7832434.html
Copyright © 2011-2022 走看看