在認(rèn)識(shí)JavaScriptCore之前,我一直以為oc和js的交互一定要通過webview才能實(shí)現(xiàn),下面直接請(qǐng)看代碼。
1,我們需要獲取文件路徑和讀取文件內(nèi)容
NSString *jsPath = [[NSBundle mainBundle] pathForResource:@"pwd-encryption"ofType:@"js"];
NSString *jsMethod = [NSString stringWithContentsOfFile:jsPath encoding:NSUTF8StringEncoding error:nil];
2.創(chuàng)建一個(gè)JSContext對(duì)象,然后將js代碼加載到context里面并且讀取這個(gè)函數(shù)對(duì)象。
SContext *context = [[JSContext alloc] init];
JSValue *jsVal = [context evaluateScript:jsMethod];
NSString * jsText =
@"var doEncrypt = function(a,b) {"
@"var f = b;"
@"var i = a;"
@"var g = i;"
@"i += \"\" + f;"
@"try {"
@"g = new RSAKey().encrypt(i)"
@"} catch (h) {"
@"return h;"
@"}"
@"return g;"
@"};";
jsVal = [context evaluateScript:jsText];
3.最后調(diào)用callWithArguments這個(gè)方法進(jìn)行參數(shù)傳值。
NSString * pwd = [NSString stringWithFormat:@"\"%@\"",@"506121"];
NSString * code = [NSString stringWithFormat:@"\"%@\"",@"1324465"];
jsVal = [context[@"doEncrypt"] callWithArguments:@[pwd, code]];
獲取到的這個(gè)jsVal可以轉(zhuǎn)化為任意類型了。注意傳參一定要用“\”隔開。