Objective-C与JavaScript交互

原理图

  • 简言
    JSContext的实例对象可以桥接两个执行环境,可以通过该实例使两个环境进行交集(类似桥梁般的存在,又称上下文对象)

依赖系统库


Objective-C向JavaScript传值

  • Objective-C实现内容
//在webViewDidFinishLoad:代理方法里获取上下文,如有需要可进行强引用
JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

//在需要传值的位置使用上下文进行传值
NSString *userId = [NSString stringWithFormat:@"%@",userManager.userId];
NSString *token = [NSString stringWithFormat:@"%@",userManager.token];
NSString *textJS = [NSString stringWithFormat:@"iOSGiveValue('%@','%@')",userId,token];
[jsContext evaluateScript:textJS];
  • JavaScript实现内容
//在写样式的位置实现函数
function giveValue(value){
   alert(value);
}

JavaScript向Objective-C传值

  • JavaScript实现内容
//在需要的位置调用Objective-C的函数
function javaScriptFunction(){
   giveValue("我是JavaScript的值,传到了Objective-C里");
}
  • Objective-C实现内容
//在webViewDidFinishLoad:代理方法里获取上下文,如有需要可进行强引用
JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

//等待JavaScript调用
jsContext[@"giveValue"] = ^(NSString *value){
    NSLog(@"%@", value);
};

你可能感兴趣的:(Objective-C与JavaScript交互)