美文网首页iOS - CordovaiOS学习iOS
iOS - JS与OC的互相调用

iOS - JS与OC的互相调用

作者: Mitchell | 来源:发表于2015-09-10 21:02 被阅读5511次
作者:Mitchell 

一 Objective - C 调用 JaveScript

  • html 代码
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
            <title>Mitchell</title>
            <script type="text/javascript">
            function show() {
                alert(1);
            }
            function showTittle() {
                alert(document.title);
            }
            function aaa() {
                location.href="https://www.baidu.com/";
            }
            function btnClick(){
                location.href="mitchell://call";
            }
            function btnClickTwo(){
                location.href="mitchell://callWithNumber_?10086";
            }
            function btnClickThree(){
                location.href="mitchell://sendMessageWithNumber_WithContent_?10086&love";
            }
            </script>
    </head>
    <body>
        <style type="text/css">
            .test {
                color: blue;
            }
        #op {
            color: orange;
        }
        
        .outer table,
        .pp {
            color: green;
        }
        
        input[type=text] {
            color: yellow;
        }
        </style>
        <div class="outer">
            <label for=“username”>姓名</label>
            <button style="background:red; height:150px; weight:150px;" onclick="btnClickThree();">哥是按钮</button>
        </div>
    </body>
</html>
  • OC 代码:
 - (void)viewDidLoad {
    [super viewDidLoad];
    NSURL*url = [[NSBundle mainBundle] URLForResource:@"test.html" withExtension:nil];
    NSURLRequest*request = [NSURLRequest requestWithURL:url];
    self.webView.delegate =self;
    [self.webView loadRequest:request];
}
 -(void)webViewDidFinishLoad:(UIWebView *)webView{
    //OC调用JS,只要利用UIWebView的stringByEvaluatingJavaScriptFromString方法,告诉系统
    [self.webView stringByEvaluatingJavaScriptFromString:@"show();"];
}

二 JaveScript调用 Objective - C

  • JS 代码同上
  • Objective - C 中的代码,这里使用了 NSInvocation 封装的一个类,下载地址
 - (void)viewDidLoad {
    [super viewDidLoad];
    NSURL*url = [[NSBundle mainBundle] URLForResource:@"test.html" withExtension:nil];
    NSURLRequest*request = [NSURLRequest requestWithURL:url];
    self.webView.delegate =self;
    [self.webView loadRequest:request];
}
//每次请求都会调用
//利用该方法作为JS和OC之间的桥梁
//JS跳转网页
//在OC代理方法中通过判断自定义协议头,决定是否是JS调用OC方法
//在OC代理方法中通过截取字符串,获取JS想调用的OC方法名称
 -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSLog(@"%@",request.URL);
    //JS调用OC 无参数
//    NSString*schem = @"mitchell://";
//    NSString*urlStr = request.URL.absoluteString;
//    if ([urlStr hasPrefix:schem]) {
//        NSLog(@"调用OC方法");
//        //1、从URL汇总获取方法名称
//        //Mitchell://call
//        NSString*methodName = [urlStr substringFromIndex:schem.length];
//        NSLog(@"%@",methodName);
//        //2、调用方法
//        SEL sel = NSSelectorFromString(methodName);
//        //下面这一行代码是用于指定忽略警告信息
//        //忽略警告信息的作用开始
//#pragma clang diagnostic push
//        //忽略的警告信息
//#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
//        [self performSelector:sel withObject:nil];
//        //忽略警告信息的作用结束
//#pragma clang diagnostic pop
//
//        return NO;
//    }
    //1个参数
//    NSString*schem = @"mitchell://";
//    NSString*urlStr = request.URL.absoluteString;
//    if ([urlStr hasPrefix:schem]) {
//        NSLog(@"调用OC方法");
//        //1、从URL汇总获取方法名称
//        NSString*subPath = [urlStr substringFromIndex:schem.length];
//        //注意:如果制定的用于切割字符串不存在,就会返回整个字符串
//        NSArray*subPaths = [subPath componentsSeparatedByString:@"?"];
//        //2、获取方法名称
//        NSString*methodName = [subPaths firstObject];
//        methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
//        NSLog(@"%@",methodName);
//        //3、调用方法
//        SEL sel = NSSelectorFromString(methodName);
//        NSString*params = nil;
//        if (subPaths.count ==2) {
//            params = [subPaths lastObject];
//        }
//        [self performSelector:sel withObject:params];
//        return NO;
//    }
    //2个参数
//    NSString*schem = @"mitchell://";
//    NSString*urlStr = request.URL.absoluteString;
//    if ([urlStr hasPrefix:schem]) {
//        NSLog(@"调用OC方法");
//        //1、从URL汇总获取方法名称
//        NSString*subPath = [urlStr substringFromIndex:schem.length];
//        //注意:如果制定的用于切割字符串不存在,就会返回整个字符串
//        //sendMessageWithNumber_WithContent_?10086&love
//        NSArray*subPaths = [subPath componentsSeparatedByString:@"?"];
//        //2、获取方法名称
//        NSString*methodName = [subPaths firstObject];
//        methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
//        //3、调用方法
//        SEL sel = NSSelectorFromString(methodName);
//        NSString*param = nil;
//        if (subPaths.count ==2) {
//            param = [subPaths lastObject];
//            //3、截取参数
//            NSArray*params = [param componentsSeparatedByString:@"&"];
//            [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
//            return NO;
//        }
//        [self performSelector:sel withObject:param];
//        return NO;
//    }
    //多个参数,这里使用了用NSInvocation封装的一个类
    NSString*schem = @"mitchell://";
    NSString*urlStr = request.URL.absoluteString;
    if ([urlStr hasPrefix:schem]) {
        NSLog(@"调用OC方法");
        //1、从URL汇总获取方法名称
        NSString*subPath = [urlStr substringFromIndex:schem.length];
        //注意:如果制定的用于切割字符串不存在,就会返回整个字符串
        //sendMessageWithNumber_WithContent_?10086&love
        NSArray*subPaths = [subPath componentsSeparatedByString:@"?"];
        //2、获取方法名称
        NSString*methodName = [subPaths firstObject];
        methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
        //3、调用方法
        SEL sel = NSSelectorFromString(methodName);
        NSArray *params = nil;
        if (subPaths.count ==2) {
            //3、截取参数
            params = [[subPaths lastObject] componentsSeparatedByString:@"&"];
            [self performSelector:sel withObjects:params];
            return NO;
        }
        [self performSelector:sel withObjects:params];
        return NO;
    }
    return YES;
}

相关文章

网友评论

  • 32fda94b118a:可以,补充一点,使用wkwebview时,在代理:
    - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
    中写js调用oc的代码
  • 回味岁月:同求swift版本的啊。。。
  • blue_man:垃圾
    OnlyLoveYu:@Mitchell 别管他 NC 喜欢出来装逼。
    superYang0033:@Mitchell 这货傻缺不用理他
    Mitchell:@blue_man 哈哈哈。我虽然第一次被这么说很气愤,但是我也很想知道原因。
  • 750fb93b380c:写的非常好,实用性很强,大神 有没有swift版本的呀。

本文标题:iOS - JS与OC的互相调用

本文链接:https://www.haomeiwen.com/subject/lvepcttx.html