1 oc 调用js
步骤1 先导入 头文件
#import <JavaScriptCore/JavaScriptCore.h>
//声明一个JSContext属性
@property (strong, nonatomic) JSContext *context;
@property (weak, nonatomic) IBOutlet UILabel *showLable;
@property (weak, nonatomic) IBOutlet UITextField *textField;
步骤2 生成jsconten他对象
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title = @"oc call js";
//生成js 对象
self.context = [[JSContext alloc] init];
//加载js 文件
[self.context evaluateScript:[self loadJsFile:@"test"]];
}
步骤3 js 文件导入
- (NSString *)loadJsFile:(NSString*)fileName
{
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"js"];
NSString *jsScript = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return jsScript;
}
test.js 文件内容
//声明js 阶乘方法
var factorial = function(n) {
if (n < 0)
return;
if (n === 0)
return 1;
return n * factorial(n - 1)
};
//声明js 平方方法
var powerMethond = function(n) {
return n*n;
};
步骤4 在oc 调用
- (IBAction)sendToJS:(id)sender {
//阶乘方法
// NSNumber *inputNumber = [NSNumber numberWithInteger:[self.textField.text integerValue]];
//
// JSValue *function = [self.context objectForKeyedSubscript:@"factorial"];//调用js方法 此方法在test.js中
// //传递参数调用js function js运算的结果
// JSValue *result = [function callWithArguments:@[inputNumber]];
// //
// self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];
//平方方法调用
NSNumber *inputNumber = [NSNumber numberWithInteger:[self.textField.text integerValue]];
JSValue *function = [self.context objectForKeyedSubscript:@"powerMethond"];//调用js方法 此方法在test.js中,方法名字要一样
//传递参数调用js function js运算的结果
JSValue *result = [function callWithArguments:@[inputNumber]];
//
self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];
}
//运算结果
2 js调用oc
声明一个协议继承于JSExport
@protocol TestJSExport <JSExport>
(calculateForJS /** handleFactorialCalculateWithNumber 作为js方法的别名 */,
- (void)handleFactorialCalculateWithNumber:(NSNumber *)number
); //方法起别名 要用()括起来
//没有别名的方法
- (void)pushViewController:(NSString *)view title:(NSString *)title;
@end
遵守协议声明属性
@interface JSCallOCViewController : UIViewController<TestJSExport>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (strong, nonatomic) JSContext *context;
@end
初始化方法 加载js
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title = @"js call oc";
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"JSCallOC.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[self.webView loadRequest:request];
}
JSCallOC.html 中部分代码js
function showResult(resultNumber)
{
//alert(resultNumber);
document.getElementById("result").innerText = resultNumber;
}
//部分截图了全部粘贴出了点问题
调用方法
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// 以 html title 设置 导航栏 title
self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
// 禁用 页面元素选择
//[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
// 禁用 长按弹出ActionSheet
//[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
// Undocumented access to UIWebView's JSContext
self.context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 打印异常
self.context.exceptionHandler =
^(JSContext *context, JSValue *exceptionValue)
{
context.exception = exceptionValue;
NSLog(@"%@", exceptionValue);
};
// 以 JSExport 协议关联 native 的方法
self.context[@"native"] = self;//协议实现关联
//[self.context evaluateScript:@"native"];
// 以 block 形式关联 JavaScript function
self.context[@"log"] =//代码块实现关联
^(NSString *str)
{
NSLog(@"%@", str);
};
// 以 block 形式关联 JavaScript function
self.context[@"alert"] =
^(NSString *str)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"msg from js" message:str delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[alert show];
};
__block typeof(self) weakSelf = self;
self.context[@"addSubView"] =
^(NSString *viewname)
{
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 500, 300, 100)];
view.backgroundColor = [UIColor redColor];
UISwitch *sw = [[UISwitch alloc]init];
[view addSubview:sw];
[weakSelf.view addSubview:view];
};
//多参数
self.context[@"mutiParams"] =
^(NSString *a,NSString *b,NSString *c)
{
NSLog(@"%@ %@ %@",a,b,c);
};
}
#pragma mark - JSExport Methods
- (void)handleFactorialCalculateWithNumber:(NSNumber *)number
{
NSLog(@"%@", number);
NSNumber *result = [self calculateFactorialOfNumber:number];
NSLog(@"%@", result);
[self.context[@"showResult"] callWithArguments:@[result]];
}
- (void)pushViewController:(NSString *)view title:(NSString *)title
{
Class second = NSClassFromString(view);
id secondVC = [[second alloc]init];
((UIViewController*)secondVC).title = title;
[self.navigationController pushViewController:secondVC animated:YES];
}
#pragma mark - Factorial Method
- (NSNumber *)calculateFactorialOfNumber:(NSNumber *)number
{
NSInteger i = [number integerValue];
if (i < 0)
{
return [NSNumber numberWithInteger:0];
}
if (i == 0)
{
return [NSNumber numberWithInteger:1];
}
NSInteger r = (i * [(NSNumber *)[self calculateFactorialOfNumber:[NSNumber numberWithInteger:(i - 1)]] integerValue]);
return [NSNumber numberWithInteger:r];
}
总结:这就是比较全面的js 和oc交互的知识点了.