Objective-C与JavaScript交互

2019-05-21  本文已影响0人  itzhaolei

原理图

依赖系统库

<JavaScriptCore/JavaScriptCore.h>

Objective-C向JavaScript传值

//在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];
//在写样式的位置实现函数
function giveValue(value){
   alert(value);
}

JavaScript向Objective-C传值

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

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

猜你喜欢

热点阅读