iOS Developer编程

iOS OC与JS 相互调用

2017-02-17  本文已影响195人  45b645c5912e

OC调用JS

//加载web  本地的一个html文件
    NSURL * url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    NSString * title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.title = title;
<script>
        function test(){
        
                alert("ceshi");
          }
 </script>
   [webView stringByEvaluatingJavaScriptFromString:@"test();"];

JS调用OC

-(id)performSelector:(SEL)aSelector withObject:(id)object;
-(id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
-(id)performSelect:(SEL)selector withObjects:(NSArray *)objects{
    //方法签名(方法描述)
    NSMethodSignature * signature = [self methodSignatureForSelector:selector];
    if (signature == nil) {
        //找不到该方法抛出异常
        @throw [NSException exceptionWithName:@"牛逼的错误" reason:@"方法找不到" userInfo:nil];
    }
    // NSInvocation : 利用一个NSInvocation对象包装一次方法调用(方法调用者、方法名、方法参数、方法返回值)
    NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:signature];
    //设置响应者
    invocation.target = self;
    //设置方法选择器
    invocation.selector = selector;
    //通过循环设置参数
    NSInteger paramsCount = signature.numberOfArguments;
    paramsCount = MIN(paramsCount, objects.count);
    for (NSInteger i = 0; i<paramsCount; i++) {
        id object = objects[i];
        if ([object isKindOfClass:[NSNull class]]) {
            continue;
        }
        [invocation setArgument:&object atIndex:i+2];
    }
    //调用方法
    [invocation invoke];
    //获取返回值
    id returnValue = nil;
    //当返回值不是空的时候
    if (signature.methodReturnLength) {
        [invocation getReturnValue:&returnValue];
    }
    return returnValue;
}
//捕获location.href的跳转信息
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    //获取跳转的URL
    NSString * url = request.URL.absoluteString;
    //自定义的协议
    NSString * scheme = @"heihei://";
    //如果url中是我们自定义的协议,实现OC中的方法
    if ([url containsString:scheme]) {
        //截取自定义协议后面的字符串
        NSString * path = [url substringFromIndex:scheme.length];
        NSString * method = nil;
        NSArray * params = nil;
        //字符串是否包含?,判断是否有参数
        if ([path containsString:@"?"]) {
            //有参数
            //通过?分割,
            NSArray * info = [path componentsSeparatedByString:@"?"];
            //数组第一个元素就是方法名,将js中的_替换为:转换为OC中的方法名
            method = [[info firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            //数组第二个元素就为参数字符串
            NSString * param = [info lastObject];
            //将参数以&分割变为参数数组
            params = [param componentsSeparatedByString:@"&"];
        }else{
            //无参数
            //方法名
            method = path;
            //参数数组
            params = @[];
        }
        NSLog(@"method:%@------params:%@",method,params);
        //通过方法签名来调用方法,因为参数的个数未知,所以我们封装一个比较通用的方法
        [self performSelect:NSSelectorFromString(method) withObjects:params];

        return NO;
    }
    return YES;
}
<script>
            function ceshi()
            {
                location.href = 'heihei://ceshi';
            }
            function ceshi1()
            {
                location.href = 'heihei://ceshi_?100';
            }
            function ceshi2()
            {
                location.href = 'heihei://ceshi_number2_?100&200';
            }
            function ceshi3()
            {
                location.href = 'heihei://ceshi_number2_number3_?100&200&300';
            }
        </script>

Demo全部代码

<html>
    <!-- 网页的描述信息 -->
    <head>
        <meta charset="UTF-8">
        <title>HeiheiJSWithOC</title>
            
        <script>
            function ceshi()
            {
                //没有参数时
                location.href = 'heihei://ceshi';
            }
            function ceshi1()
            {
                //一个参数时
                location.href = 'heihei://ceshi_?100';
            }
            function ceshi2()
            {
                //二个参数时
                location.href = 'heihei://ceshi_number2_?100&200';
            }
            function ceshi3()
            {
                //三个参数时
                location.href = 'heihei://ceshi_number2_number3_?100&200&300';
            }
            function test(){
        
                alert("ceshi");
            }
        </script>
    </head>
    <!-- 网页的具体内容 -->
    <body>
        <div>电话:10086</div>
        <br>
        <button style="color:white ;background-color: red; width:100px; height:30px; margin-top:5px" onclick="ceshi();">测试无参数</button>
        <br>
        <button style="color:white ;background-color: red; width:100px; height:30px; margin-top:5px" onclick="ceshi1();">测试1个参数</button>
        <br>
        <button style="color:white ;background-color: red; width:100px; height:30px; margin-top:5px" onclick="ceshi2();">测试2个参数</button>
        <br>
        <button style="color:white ;background-color: red; width:100px; height:30px; margin-top:5px" onclick="ceshi3();">测试3个参数</button>
        <br>
        <a href="http://www.baidu.com">百度</a>
    </body>
</html>
//
//  ViewController.m
//  OCWithJS
//
//  Created by zzh on 2017/2/17.
//  Copyright © 2017年 zzh. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
@implementation ViewController
-(void)viewDidLoad {
    [super viewDidLoad];
    //加载web  本地的一个html文件
    NSURL * url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
}
#pragma mark - 不同参数的测试方法
-(void)ceshi{    
    NSLog(@"%s----无参数", __func__);    
}
-(void)ceshi:(NSString *)number1{   
    NSLog(@"%s----%@---", __func__,number1);    
}
-(void)ceshi:(NSString *)number1 number2:(NSString *)number2{    
    NSLog(@"%s----%@---%@--", __func__,number1,number2);   
}
-(void)ceshi:(NSString *)number1 number2:(NSString *)number2 number3:(NSString *)number3{   
    NSLog(@"%s----%@---%@---%@---", __func__,number1,number2,number3);    
}
#pragma mark - UIWebViewDelegate
//捕获location.href的跳转信息
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    //获取跳转的URL
    NSString * url = request.URL.absoluteString;
    //自定义的协议
    NSString * scheme = @"heihei://";
    //如果url中是我们自定义的协议,实现OC中的方法
    if ([url containsString:scheme]) {
        //截取自定义协议后面的字符串
        NSString * path = [url substringFromIndex:scheme.length];
        NSString * method = nil;
        NSArray * params = nil;
        //字符串是否包含?,判断是否有参数
        if ([path containsString:@"?"]) {
            //有参数
            //通过?分割,
            NSArray * info = [path componentsSeparatedByString:@"?"];
            //数组第一个元素就是方法名,将js中的_替换为:转换为OC中的方法名
            method = [[info firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            //数组第二个元素就为参数字符串
            NSString * param = [info lastObject];
            //将参数以&分割变为参数数组
            params = [param componentsSeparatedByString:@"&"];
        }else{
            //无参数
            //方法名
            method = path;
            //参数数组
            params = @[];
        }
        NSLog(@"method:%@------params:%@",method,params);
        //通过方法签名来调用方法,因为参数的个数未知,所以我们封装一个比较通用的方法
        [self performSelect:NSSelectorFromString(method) withObjects:params];

        return NO;
    }
    return YES;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    //oc调用js
    NSString * title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.title = title;
   [webView stringByEvaluatingJavaScriptFromString:@"test();"];
}
#pragma mark - 根据方法签名调用方法
-(id)performSelect:(SEL)selector withObjects:(NSArray *)objects{
    //方法签名(方法描述)
    NSMethodSignature * signature = [self methodSignatureForSelector:selector];
    if (signature == nil) {
        //找不到该方法抛出异常
        @throw [NSException exceptionWithName:@"牛逼的错误" reason:@"方法找不到" userInfo:nil];
    }
    // NSInvocation : 利用一个NSInvocation对象包装一次方法调用(方法调用者、方法名、方法参数、方法返回值)
    NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:signature];
    //设置响应者
    invocation.target = self;
    //设置方法选择器
    invocation.selector = selector;
    //通过循环设置参数
    NSInteger paramsCount = signature.numberOfArguments;
    paramsCount = MIN(paramsCount, objects.count);
    for (NSInteger i = 0; i<paramsCount; i++) {
        id object = objects[i];
        if ([object isKindOfClass:[NSNull class]]) {
            continue;
        }
        [invocation setArgument:&object atIndex:i+2];
    }
    //调用方法
    [invocation invoke];
    //获取返回值
    id returnValue = nil;
    //当返回值不是空的时候
    if (signature.methodReturnLength) {
        [invocation getReturnValue:&returnValue];
    }
    return returnValue;
}
@end
上一篇 下一篇

猜你喜欢

热点阅读