设为首页 加入收藏

TOP

OC与JS的交互
2017-10-13 10:17:14 】 浏览:4822
Tags:交互

现在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; width: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这个协议

利用stringByeva luationgjava scriptFromString这个协议方法,

可以完成OC调用JS

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

3.

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

/**
 * 通过这个方法完成JS调用OC
 * 第三方框架 :WebViewjava scriptBridge
 */
- (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/WebViewjava scriptBridge

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇UIWebView中JS与OC交互 WebViewJa.. 下一篇纯Swift编写的仿“随遇”应用源码

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目