JavaScript与OC交互 方案和概要

JavaScript与OC交互

JavaScript与OC交互

IO7之前 -- stringByEvaluatingJavaScriptFromString

  • 你只能通过向UIWebView发送stringByEvaluatingJavaScriptFromString:消息来执行一段JavaScript脚本。
  • 并且如果想用JavaScript调用Objective-C,必须打开一个自定义的URL(例如:foo://),然后在UIWebView的delegate方法webView:shouldStartLoadWithRequest:navigationType中进行处理。

IOS 7之后 --JavaScriptCore

可以利用JavaScriptCore的先进功能了, 它可以:

  • 运行JavaScript脚本而不需要依赖UIWebView
  • 使用现代Objective-C的语法(例如Blocks和下标)
  • 在Objective-C和JavaScript之间无缝的传递值或者对象
  • 创建混合对象(原生对象可以将JavaScript值或函数作为一个属性)

Demo地址: CPYJSCoreDemo

JavaScriptCore概述:

  • JSValue: 代表一个JavaScript实体,一个JSValue可以表示很多JavaScript原始类型例如boolean, integers, doubles,甚至包括对象和函数。
  • JSManagedValue: 本质上是一个JSValue,但是可以处理内存管理中的一些特殊情形,它能帮助引用技术和垃圾回收这两种内存管理机制之间进行正确的转换。
  • JSContext: 代表JavaScript的运行环境,你需要用JSContext来执行JavaScript代码。所有的JSValue都是捆绑在一个JSContext上的。
  • JSExport: 这是一个协议,可以用这个协议来将原生对象导出给JavaScript,这样原生对象的属性或方法就成为了JavaScript的属性或方法,非常神奇。
  • JSVirtualMachine: 代表一个对象空间,拥有自己的堆结构和垃圾回收机制。大部分情况下不需要和它直接交互,除非要处理一些特殊的多线程或者内存管理问题。

核心代码:

1.初始化JavaScript的运行环境JSContext

JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    //异常处理
    //当JavaScript运行时出现异常,会回调JSContext的exceptionHandler中设置的Block
    [context setExceptionHandler:^(JSContext *ctx, JSValue *expectValue) {
        NSLog(@"%@", expectValue);
    }];
    
    self.context = context;

2.JavaScript调用Objective-C

//JavaScript调用Objective-C
    __weak typeof(self) weakSelf = self;
    //ocAlert 为 JavaScript方法
    self.context[@"ocAlert"] = ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong typeof(weakSelf) strongSelf = weakSelf;
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"这是OC中的弹框!" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [alert dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }]];
            [strongSelf.navigationController presentViewController:alert animated:YES completion:nil];
        });
    };

3.Objective-C调用JavaScript方法

- (IBAction)buttonClick:(UIButton *)sender {
    if (!self.context) {
        return;
    }
    //Objective-C调用JavaScript  alertFunc为JavaScript方法
    //通过条用JSValue - (JSValue *)evaluateScript:(NSString *)script;
    //方法就可以执行一段JavaScript脚本,并且如果其中有方法、变量等信息都会被存储在其中以便在需要的时候使用。
    JSValue *funcValue = self.context[@"alertFunc"];
    [funcValue callWithArguments:nil];
}

使用第三方交互框架 -- WebViewJavascriptBridge

github:WebViewJavascriptBridge

posted @ 2016-06-29 20:18  niwanglong385  阅读(113)  评论(0)    收藏  举报