.js
文件中的代码:
var fact = function(x){
return WeatherWebService(x);
}
Objective-C原生方法:
- (IBAction)btnOkClicked:(id)sender
{
[self.aJSEngine loadJSLibrary:@"script"];
}
- (void)loadJSLibrary:(NSString*)libraryName
{
NSString *library = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:libraryName ofType:@"js"] encoding:NSUTF8StringEncoding error:nil];
NSLog(@"[JSC] loading library %@...", libraryName);
[self runJS:library];
}
- (void)runJS:(NSString *)aJSString
{
if (!aJSString) {
NSLog(@"[JSC] JS String is empty!");
}
else{
JSContext *context = [[JSContext alloc]initWithVirtualMachine:[[JSVirtualMachine alloc]init]];
context[@"WeatherWebService"] = ^(int x){
NSDictionary *dict = [self callingWeatherFromJavascript];
return dict;
};
[context evaluateScript:aJSString];
JSValue *val = context[@"fact"];
JSValue *finalResult = [val callWithArguments:@[context[@"3"]]];
}
}
-(NSDictionary*)callingWeatherFromJavascript{
NSString *urlString = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
__block BOOL complete = NO;
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// 3
self.dictionary = (NSDictionary *)responseObject;
complete=YES;
// NSDictionary *dict = [self.dictionary objectForKey:@"main"];
// if ([self.delegate respondsToSelector:@selector(returnDataFromResponse:)]) {
// [self.delegate returnDataFromResponse:dict];
// }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
complete=NO;
[alertView show];
}];
// 5
[operation start];
while(complete == NO) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
return self.dictionary;
}
在上面的代码中,方法
'callingWeatherFromJavascript'
返回NSDictionary
。当我在'-(void)runJS'
函数的“JSValue”中接收到此值时,它将返回[object Object]
。有什么办法可以将其转换回NSDictionary
吗? 最佳答案
我不想忘记vivek_ios,他回答了自己的问题。我只想重写他的回答,以便更清晰,更轻松地重复使用,因为我花了一段时间才能在评论中找到答案。
基本上,将JSValue转换为NSDictionary只需通过JSValue.toDictionary完成。像这样:
JSContext *jsContext = [JSContext new];
[jsContext evaluateScript:[NSString stringWithContentsOfFile:myJavascriptFilePath encoding:NSUTF8StringEncoding error:nil]];
NSDictionary *result = [jsContext[@"myJavascriptFunction"] callWithArguments:@[optionalArgument]].toDictionary;
关于javascript - 使用javascriptcore框架调用javascript函数会将[object Object]返回给JSValue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23606595/