问题是您已将回调定义为采用 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