How to call JavaScript Function in objective C

后端 未结 5 1683
借酒劲吻你
借酒劲吻你 2020-12-01 04:09

I am new programmer to objective C. I added some html file to Objective C. In this html file contains simple javascript function. I need to call that Function through thw ob

5条回答
  •  温柔的废话
    2020-12-01 04:20

    FileName.js :

    function greet() {
        hello(“This is Javascript function!”);
    }
    

    Copy this file into Bundle resources.

    Now #import in header file

     @property (nonatomic,strong) JSContext *context; // Declare this in header file
    
           // This code block goes into main file
            NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"js"];
            NSString *scriptString = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];
    
            self.context = [[JSContext alloc] init];
            [self.context evaluateScript:scriptString];
    
            self.context[@"hello"] = ^(NSString text) {
                NSLog(@"JS : %@",text);
            }
    
            JSValue *function = self.context[@"greet"];
            [function callWithArguments:@[]];
    

    This code block worked for me. It displays "This is Javascript function!" in console. Hope this works!

提交回复
热议问题