1 ??oc 調(diào)用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 文件內(nèi)容
//聲明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 調(diào)用
- (IBAction)sendToJS:(id)sender {
//階乘方法
//? ? NSNumber *inputNumber = [NSNumber numberWithInteger:[self.textField.text integerValue]];
//
//? ? JSValue *function = [self.context objectForKeyedSubscript:@"factorial"];//調(diào)用js方法 此方法在test.js中
//? ? //傳遞參數(shù)調(diào)用js function js運算的結(jié)果
//? ? JSValue *result = [function callWithArguments:@[inputNumber]];
//? ? //
//? ? self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];
//平方方法調(diào)用
NSNumber *inputNumber = [NSNumber numberWithInteger:[self.textField.text integerValue]];
JSValue *function = [self.context objectForKeyedSubscript:@"powerMethond"];//調(diào)用js方法 此方法在test.js中,方法名字要一樣
//傳遞參數(shù)調(diào)用js function js運算的結(jié)果
JSValue *result = [function callWithArguments:@[inputNumber]];
//
self.showLable.text = [NSString stringWithFormat:@"%@", [result toNumber]];
}
//運算結(jié)果
2 ?js調(diào)用oc
聲明一個協(xié)議繼承于JSExport
@protocol TestJSExport <JSExport>
(calculateForJS? /** handleFactorialCalculateWithNumber 作為js方法的別名 */,
- (void)handleFactorialCalculateWithNumber:(NSNumber *)number
); //方法起別名 要用()括起來
//沒有別名的方法
- (void)pushViewController:(NSString *)view title:(NSString *)title;
@end
遵守協(xié)議聲明屬性
@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;
}
? ?
//部分截圖了全部粘貼出了點問題
?調(diào)用方法
#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 協(xié)議關聯(lián) native 的方法
self.context[@"native"] = self;//協(xié)議實現(xiàn)關聯(lián)
//[self.context evaluateScript:@"native"];
// 以 block 形式關聯(lián) JavaScript function
self.context[@"log"] =//代碼塊實現(xiàn)關聯(lián)
^(NSString *str)
{
NSLog(@"%@", str);
};
// 以 block 形式關聯(lián) 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];
};
//多參數(shù)
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];
}
總結(jié):這就是比較全面的js 和oc交互的知識點了.