JS与OC原生方法互相调用

本文将通过JavaScriptCore提供的方法,实现JS调用OC原生方法和OC中调用JS方法等


1.导入JavaScriptCore
#import <JavaScriptCore/JavaScriptCore.h>
2.定义全局的JSContext对象
@property(nonatomic,strong) JSContext *jsContext;
3.获取webview的上下文

页面加载完成时,获取webview的上下文 ,并将对象注入js内

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //获取webview的上下文
    self.jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //将对象注入js内,在JS中便可使用"ocObject"来调用oc的方法了
    self.jsContext[@"ocObject"] = self;
}
4.定义与js交互的协议

只有在这个协议中声明并实现的方法,才能够在js中调用

// JSExport 定义与js交互的协议
@protocol JSExportDelagte <JSExport>
-(void)ocFunction:(NSString *)string;
@end

#pragma -mark JSExportDelagte
-(void)ocFunction:(NSString *)string{
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [av show];
}
5.js可以调用OC的原生方法了
//js
<script type="text/javascript">
     function fun1() {
            var string = "oc方法调用成功";
            //调用oc的方法
            ocObject.ocFunction(string);
     }
</script>
6.OC调用js方法

通过JSValue获取js方法并调用

//js
<script type="text/javascript">
     //被oc调用的js方法
     var jsFunction = function(){
         alert('js方法调用成功');
     } 
</script>
//oc
-(void)ocCallJSFunction{
    //在oc中调用js方法
    JSValue *jsValue = self.jsContext[@"jsFunction"];
    [jsValue callWithArguments:nil];
}
7.通过block可以传递多个参数
//oc
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    //在页面加载完成时,获取webview的上下文 ,并将对象注入js内
    self.jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    //使用block 可以实现多个参数传递(由js传递到oc)
    self.jsContext[@"ocBlock"] = ^(NSString *name,NSString *age) {
        NSString *info = [NSString stringWithFormat:@"我的名字叫做:%@,今年%@岁了!",name,age];
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"提示" message:info delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [av show];
    };
}
//js
<script type="text/javascript">
     function fun3() {
          ocBlock('小明','7');
     } 
</script>

Demo代码

ViewController.m

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>

// JSExport 定义与js交互的协议
@protocol JSExportDelagte <JSExport>
-(void)ocFunction:(NSString *)string;
-(void)ocCallJSFunction;
@end

@interface ViewController ()<UIWebViewDelegate,JSExportDelagte>
@property(nonatomic,strong) UIWebView *webView;
@property(nonatomic,strong) JSContext *jsContext;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.webView];
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    self.webView.delegate = self;
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    //在页面加载完成时,获取webview的上下文 ,并将对象注入js内
    self.jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //在js中,便可使用ocObject来调用oc中的方法了
    self.jsContext[@"ocObject"] = self;
    
    //使用block 可以实现多个参数传递(由js传递到oc)
    self.jsContext[@"ocBlock"] = ^(NSString *name,NSString *age) {
        NSString *info = [NSString stringWithFormat:@"我的名字叫做:%@,今年%@岁了!",name,age];
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"提示" message:info delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [av show];
    };
}

#pragma -mark JSExportDelagte
-(void)ocFunction:(NSString *)string{
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [av show];
}
-(void)ocCallJSFunction{
    //在oc中调用js方法
    JSValue *jsValue = self.jsContext[@"jsFunction"];
    [jsValue callWithArguments:nil];
}

-(void)sumA:(int)a andB:(int)b{
    NSString *s = [NSString stringWithFormat:@"%d+%d=%d",a,b,a+b];
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"计算结果" message:s delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [av show];
}

@end

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
            <title>index</title>
            <script type="text/javascript">
                function fun1() {
                    var string = "oc方法调用成功";
                    //调用oc的方法
                    ocObject.ocFunction(string);
                    
                }
                function fun2() {
                    ocObject.ocCallJSFunction();
                }
                function fun3() {
                    ocBlock('小明','7');
                }
                //被oc调用的js方法
                var jsFunction = function(){
                    alert('js方法调用成功');
                }
            </script>
            <script type="text/javascript" src="javaScript.js"></script>
            <style type="text/css">
                .box{
                    margin-left: 40px;
                    width: 300px;
                    height: 100px;
                    background-color: deeppink;
                    padding-top: 10px;
                    padding-left: 10px;
                    padding-right: 10px;
                    padding-bottom: 10px;
                }
            #div1{
                margin-top: 100px;
            }
            #div2{
                margin-top: 0px;
            }
            #div3{
                margin-top: 0px;
            }
            
                </style>
    </head>
    <body>
        <div id="div1" class="box">
            <input type="button" style="width: 300px;height: 100px;background-color: yellow" value="js调用oc方法" onclick="fun1()"/>
        </div>
        <div id="div2" class="box">
            <input type="button" style="width: 300px;height: 100px;background-color: yellow" value="oc调用js方法" onclick="fun2()"/>
        </div>
        <div id="div3" class="box">
            <input type="button" style="width: 300px;height: 100px;background-color: yellow" value="通过oc代码块实现js传递多个参数到oc方法中" onclick="fun3()"/>
        </div>
    </body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 随着H5技术的兴起,在iOS开发过程中,难免会遇到原生应用需要和H5页面交互的问题。其中会涉及方法调用及参数传值等...
    Chris_js阅读 8,286评论 1 8
  • 本文由我们团队的 纠结伦 童鞋撰写。 写在前面 本篇文章是对我一次组内分享的整理,大部分图片都是直接从keynot...
    知识小集阅读 15,337评论 11 172
  • 注:本文copy自http://www.jianshu.com/p/ac534f508fb0,纯属当笔记使用。 概...
    BookKeeping阅读 4,035评论 1 3
  • 写在前面 本篇文章是对我一次组内分享的整理,大部分图片都是直接从keynote上截图下来的,本来有很多炫酷动效的,...
    等开会阅读 14,896评论 6 69
  • 有时候,真的 其实只是寂寞而已 只是偶尔会希望自己可以想起一个人 像是夜风中的一盏路灯 可以倾诉 或者是街头一只走...
    嘻嘻哈呀阅读 1,267评论 1 0