美文网首页
浅谈oc与js交互(二 UIWebView中 js调用oc)

浅谈oc与js交互(二 UIWebView中 js调用oc)

作者: 神经嘻嘻兮兮 | 来源:发表于2017-06-19 15:42 被阅读102次

    上篇文章讲过,oc和js交互,oc调用js关键的方法是
    - (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;
    这篇文章讲的是js如何调用oc,js调用oc的关键方法是
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

    一、写一个简单的html网页,3个p标签。


    372E5D6D-6840-4D6F-928E-49F6583927C2.png

    js代码

    image.png

    二、实现UIWebViewDelegate的代理方法。
    request.URL.scheme 协议。
    request.URL.absoluteString 绝对路径。
    //每当webView即将发送一个请求之前,都会调用这个方法

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSLog(@"scheme = %@",request.URL.scheme);
    NSLog(@"absoluteString = %@",request.URL.absoluteString);
    NSArray *array = [request.URL.absoluteString componentsSeparatedByString:@"?"];
    NSLog(@"array = %@",array);
    //判断连接是否存在
    if ([request.URL.scheme isEqualToString:@"clickp"]) {
        //说明没有参数
        if (array.count==1) {
    
            SEL sel = NSSelectorFromString(request.URL.scheme);
            [self performSelector:sel withObject:nil withObject:nil];
    
        }else if(array.count == 2){//说明有1个参数
    
            SEL sel = NSSelectorFromString([NSString stringWithFormat:@"%@:",request.URL.scheme]);
            [self performSelector:sel withObject:[array lastObject] withObject:nil];
    
        }else if (array.count == 3){//说明有2个参数
    
            SEL sel = NSSelectorFromString([NSString stringWithFormat:@"%@:message:",request.URL.scheme]);
            [self performSelector:sel withObject:array[1] withObject:[array lastObject]];
    
        }
    
    }
    

    三、点击p标签,执行UIWebViewDelegate的代理方法,调用oc代码

    //点击第一个p标签
    - (void)clickp{
    self.showTop.text = @"点击了第一个p标签";
    }

    //点击第二个p标签
    - (void)clickp:(NSString *)message{
    NSString *new = [message stringByRemovingPercentEncoding];
    self.showCenter.text = new;
    }

    //点击第三个p标签

    - (void)clickp:(NSString *)firstMessage message:(NSString *)lastMessage{
    NSString *firstParam = [firstMessage stringByRemovingPercentEncoding];
    NSString *lastParam = [lastMessage stringByRemovingPercentEncoding];
    self.showBottom.text = [NSString stringWithFormat:@"%@ %@",firstParam,lastParam];
    }
    

    实例图片:

    jscalloc.gif
    github地址:https://github.com/shimminZ/JsCallOC.git
    欢迎star.

    相关文章

      网友评论

          本文标题:浅谈oc与js交互(二 UIWebView中 js调用oc)

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