使用javascriptcore框架调用javascript函数会将[object Object]返回给JSValue

时间:2014-05-12 10:27:17

标签: javascript ios objective-c javascriptcore

.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

2 个答案:

答案 0 :(得分:2)

我不想从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;

答案 1 :(得分:0)

首先将您的响应对象转换为NSData

NSData *responseData = [[NSData alloc]initWithContentsOfFile:(NSString*)responseObject encoding:NSUTF8StringEncoding error:nil];

然后使用JSON序列化创建NSDictionary,因为它看起来像是从Web服务接收JSON对象

NSDictionary *responceDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];

然后你应该能够访问你的" main"键,从这里获取所有信息。