zoukankan      html  css  js  c++  java
  • OC与JS的交互

    现在APP的开发已经不局限于原生开发,很多都是原生+html5这种混合开发

    我们可以通过webView这个控件,实现混合开发。

    1.首先你需要创建一个html页面

    <html>
        <head>
            <meta charset="utf-8">
            <title>第一个页面</title>
        </head>
        
        <script>
            function login() {
                location.href = 'ddz://call_?200';
            }
        </script>
        
        <body>
            <button style="background: blue; 100px; height:30px" onclick="login()">确定</button>
            <br>
            <a href="http://www.baidu.com">百度</a>
        </body>
    </html>

    在app初始化时,加载这个页面

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]]];
    }

    2.实现UIWebViewDelegate这个协议

    利用stringByEvaluationgJavaScriptFromString这个协议方法,

    可以完成OC调用JS

    #pragma mark - <UIWebViewDelegate>
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        [webView stringByEvaluatingJavaScriptFromString:@"alert(100)"];
    }

    3.

    利用shouldStartLoadWithRequest这个方法可以完成JS调用OC

    /**
     * 通过这个方法完成JS调用OC
     * 第三方框架 :WebViewJavaScriptBridge
     */
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
        //url = ddz://sendMessage_?200
        NSString *url = request.URL.absoluteString;
        NSString *scheme = @"ddz://";
        if ([url hasPrefix:@"ddz://"]) {
            NSLog(@"调用OC的方法");
            
            //获得协议后面的路径 path = sendMessage_?200
            NSString *path = [url substringFromIndex:scheme.length];
            //利用?进行切割
            NSArray *subpaths = [path componentsSeparatedByString:@"?"];
            //方法名 methodName = sendMessage:
            NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            //参数 params = 200
            NSString *params = [subpaths lastObject];
            
            [self performSelector:NSSelectorFromString(methodName) withObject:params];
    //        NSLog(@"%@",subpaths);
            return NO;
        }
        
        NSLog(@"想加载其他请求,不是想调用OC的方法");
        
        return YES;
    }

    4.

    在github上也找到了一个 oc 和 js 之间能够交互的类,可以看一下 https://github.com/marcuswestin/WebViewJavascriptBridge

  • 相关阅读:
    给力牛人
    设计模式
    微软真的要放弃Windows品牌吗?
    SQL2005 Express 自动安装之命令行
    SQL where之 in 在变量
    数据库求闭包,求最小函数依赖集,求候选码,判断模式分解是否为无损连接,3NF,BCNF
    别浪费了你的大内存[转]
    QQ空间免费养5级花和拥有人参果
    asp.net2 统一搜索引擎关键字编码[转]
    把网速提高4倍的方法和动画教程
  • 原文地址:https://www.cnblogs.com/langji/p/5394308.html
Copyright © 2011-2022 走看看