iOS 的JS 和 OC 交互(一)

  • OC 调用 JS
  • JS 调用OC
  1. 预备工作
    首先要 导入 JavaScriptCore.framework 这个库,然后用来的类 分别是 JSContext , JSValue , JSExport 。

  2. 再来一个 test.html 部分代码

<a href="#" id="test">JS call OC</a>
    <style>
        a {
            display: block;
            width: 100px;
            height: 50px;
            text-align: center;
            background: red;
            color: #fff;
            line-height: 50px;
            text-decoration: none;
        }
    </style>
    <script>
        document.getElementById('test').onclick = function(){
              //这个方法是 用来 测试 JS调用 OC 的
             // IOS_Obj 是什么来的?what ?
             //不要急,搜索复制粘贴看看,这个类我放在下面也贴出来了
            var a = IOS_Obj.getUser();
            alert(a);
        }
    
    function ocCallJS()
    {
        alert('OC Call JS');
    }
    
    function ocCallJSWithArg(a,b)
    {
        alert('a:'+ a +'   '+'b:'+b);
    }
  1. 有了 html ,那么我们 还需要一个 UIWebView
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height)];
_webView.delegate = self;
[self.view addSubview:_webView];
  1. 然后加载上这个html
    这个html 是放在项目里面 的 也可以是 放在服务器 然后读取

放在项目里面的读取方式

 NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
 NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"];
 NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
 [_webView loadHTMLString:html baseURL:baseURL];

读取一个URL 是 这样读的

[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"你的html 所在的URL"]]];
  1. 说说这个JSContext 是怎样获取的
self.context = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    self.context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        [JSContext currentContext].exception = exception;
        NSLog(@"exception:%@",exception);
    };
    
    self.obj = [[IOS_Obj alloc] init];
    self.context[@"IOS_Obj"] = self.obj;
//self.context[@"这个值可以自由定义,自定好了告诉JS 就好"] 
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//为什么这里也要写一个呢?
//因为当跳转到另外一个html 的时候 self.context 里面的对象被清空了
    self.context[@"IOS_Obj"] = self.obj;
}
  1. 再准备两个按钮 用来测试
UIButton *firstBtn = [UIButton buttonWithType:UIButtonTypeCustom];
   firstBtn.frame = CGRectMake(20, 20, 100, 30);
   firstBtn.backgroundColor = [UIColor purpleColor];
   [firstBtn addTarget:self action:@selector(firstBtnAction) forControlEvents:UIControlEventTouchUpInside];
   [firstBtn setTitle:@"OC Call JS" forState:UIControlStateNormal];
   firstBtn.titleLabel.font = [UIFont systemFontOfSize:10];
   [self.view addSubview:firstBtn];

   UIButton *secondBtn = [UIButton buttonWithType:UIButtonTypeCustom];
   secondBtn.frame = CGRectMake(CGRectGetMaxX(firstBtn.frame) + 30, 20, 150, 30);
   secondBtn.backgroundColor = [UIColor purpleColor];
   [secondBtn addTarget:self action:@selector(secondBtnAciton) forControlEvents:UIControlEventTouchUpInside];
   [secondBtn setTitle:@"OC Call JS With Arg" forState:UIControlStateNormal];
   secondBtn.titleLabel.font = [UIFont systemFontOfSize:10];
   [self.view addSubview:secondBtn];
  1. JS 调用OC 还要准备一个类,一个实现了JSExport 协议的类
    h文件
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
@protocol JSExportForIOS <JSExport>
-(NSString *)getUser;
@end
@interface IOS_Obj : NSObject<JSExportForIOS>
@end

m文件

@implementation IOS_Obj
//请头回看看上面的 html 里面的代码 
-(NSString *)getUser
{
    return @"hello xixi";
}  
@end
  1. 最后看看 之前的Button 里面写了啥东西

这里面我写了两种调用 OC 调用JS 的方法,亲测有效

-(void) firstBtnAction
{
    //方法一
//    JSValue *function = [self.context objectForKeyedSubscript:@"ocCallJS"];
//    JSValue *result = [function callWithArguments:nil];
    //方法二
    NSString *alertJS = @"ocCallJS()";
    [self.context evaluateScript:alertJS];
}
-(void) secondBtnAciton
{
  //方法一
//    JSValue *function = [self.context objectForKeyedSubscript:@"ocCallJSWithArg"];
//    JSValue *result = [function callWithArguments:[NSArray arrayWithObjects:@"one Arg",@"two Arg", nil]];
    //方法二
    NSString *alertJS = @"ocCallJSWithArg('one Arg','two Arg')"; 
    [self.context evaluateScript:alertJS];
}
  1. 最后有图有真相
    js_call_oc


    JS_CALL_OC.png

oc_call_js


OC_CALL_JS.png

oc_call_js_with_arg


OC_CALL_JS_with_arg.png

PS: JS调用OC 的方法: 有时候在加载了html 渲染之后 才能触发UIWebView 的 -(void)webViewDidFinishLoad:(UIWebView *)webView 的代理方法,然而我要在这个代理方法里面 设置 JSContext ,那也只能让JS 在unload 做一下 延迟100毫秒左右就好。

iOS 的JS 和 OC 交互(二)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容