JavascriptCore:在 JSExport 中将 javascript 函数作为参数传递

2024-05-13

JavascriptCore是iOS7中支持的新框架。我们可以使用 JSExport 协议将 objc 类的部分内容公开给 JavaScript。

在javascript中,我尝试将函数作为参数传递。像这样:

function getJsonCallback(json) {
        movie = JSON.parse(json)
        renderTemplate()
}
viewController.getJsonWithURLCallback("", getJsonCallback)

在我的 objc viewController 中,我定义了我的协议:

@protocol FetchJsonForJS <JSExport>
 - (void)getJsonWithURL:(NSString *)URL
               callback:(void (^)(NSString *json))callback;
 - (void)getJsonWithURL:(NSString *)URL
         callbackScript:(NSString *)script;
@end

在javascript中,viewController.getJsonWithURLCallbackScript可以工作,但是,viewController.getJsonWithURLCallback不能工作。

我在 JSExport 中使用 block 有什么错误吗?谢谢。


问题是您已将回调定义为采用 NSString arg 的 Objective-C 块,但 javascript 不知道如何处理它,并在您尝试评估 viewController.getJsonWithURLCallback("", getJsonCallback) 时产生异常 - 它认为第二个参数的类型是“未定义”

相反,您需要将回调定义为 JavaScript 函数。

您可以在 Objective-C 中使用 JSValue 来完成此操作。

对于其他读者,这里有一个完整的工作示例(带有异常处理):

TestHarnessViewController.h:

#import <UIKit/UIKit.h>
#import <JavaScriptCore/JavaScriptCore.h>

@protocol TestHarnessViewControllerExports <JSExport>
- (void)getJsonWithURL:(NSString *)URL callback:(JSValue *)callback;
@end

@interface TestHarnessViewController : UIViewController <TestHarnessViewControllerExports>
@end

TestHarnessViewController.m:(如果使用复制/粘贴,请删除评估脚本内的换行符 - 添加这些换行符是为了清楚起见):

#import "TestHarnessViewController.h"

@implementation TestHarnessViewController {
    JSContext *javascriptContext;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    javascriptContext  = [[JSContext alloc] init];
    javascriptContext[@"consoleLog"] = ^(NSString *message) {
        NSLog(@"Javascript log: %@",message);
    };
    javascriptContext[@"viewController"] = self;

    javascriptContext.exception = nil;
    [javascriptContext evaluateScript:@"
        function getJsonCallback(json) {
            consoleLog(\"getJsonCallback(\"+json+\") invoked.\");
            /* 
            movie = JSON.parse(json); 
            renderTemplate(); 
            */
        } 

        viewController.getJsonWithURLCallback(\"\", getJsonCallback);
    "];
    JSValue *e = javascriptContext.exception;
    if (e != nil && ![e isNull])
        NSLog(@"Javascript exception occurred %@", [e toString]);
}

- (void)getJsonWithURL:(NSString *)URL callback:(JSValue *)callback {
    NSString *json = @""; // Put JSON extract from URL here
    [callback callWithArguments:@[json]];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavascriptCore:在 JSExport 中将 javascript 函数作为参数传递 的相关文章