假设我有一个 javascript 文件 javascript.js
,其中包含以下内容。
window.fruitsAndVeggies = {
name2CategoryMap: {
"apple": "fruit",
"carrot": "vegetable"
}
}
谁能告诉我将 Javascript 对象 window.fruitsAndVeggies
的内容放入 NSDictionary 中的最简单方法?
我从互联网上的各种来源拼凑了以下代码片段,它创建了一个 Javascript 上下文,然后在该上下文中评估 javascript 代码。
JSGlobalContextRef ctx = JSGlobalContextCreate(NULL); // create context
JSValueRef exception = JSValueMakeUndefined(ctx); // create object to hold exceptions
// Make a "window" object in the JS Context
JSStringRef makeWindowScript = JSStringCreateWithUTF8CString("var window = {}");
JSValueRef result = JSEvaluateScript( ctx, makeWindowScript, NULL, NULL, 0, &exception );
// load the javascript file into an NSString
NSBundle * bundle = [NSBundle bundleWithIdentifier:@"my.bundle"];
NSString *filePath = [bundle pathForResource:@"javascript" ofType:@"js"];
NSError *error;
NSString *stringFromFile = [[NSString alloc]
initWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
// convert NSString to a JSStringRef
CFStringRef cfString = (__bridge CFStringRef)stringFromFile;
JSStringRef jsString = JSStringCreateWithCFString(cfString);
// evaluate the javascript
JSEvaluateScript( ctx, jsString, NULL, NULL, 0, &exception );
我对下一步该做什么感到困惑。我需要在我的 objective-c 代码中使用 fruitsAndVeggies.name2CategoryMap
的内容。访问它们的最简单方法是什么?我可以调用一个简单的函数来将它们加载到 Objective-C 字典中吗?
非常感谢您的帮助。
最佳答案
自从 iOS 7 引入 JavaScriptCore 中的新 Objective-C 接口(interface)以来,事情变得简单多了。有关此内容的介绍,请参阅 Apple 开发者网络上的 WWDC 2013 session “将 JavaScript 集成到 native 应用程序” session :https://developer.apple.com/videos/wwdc/2013/?id=615
评估javascript资源文件后需要的代码是:
JSContext *context = [JSContext contextWithJSGlobalContextRef:ctx];
NSDictionary *fruitsAndVeggiesDict = [context[@"window"][@"fruitsAndVeggies"][@"name2CategoryMap"] toObject];
NSLog(@"name2CategoryMap['apple'] = %@", fruitsAndVeggiesDict[@"apple"]);
NSLog(@"name2CategoryMap['carrot'] = %@", fruitsAndVeggiesDict[@"carrot"]);
关于javascript - 如何使用 JavaScriptCore 将 javascript 对象转换为 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749248/