终于想通了这一点。可能有更好的方法(如果是这样,请加上!)但以下似乎工作。在我的OBJ-C(NSObject
派生)类 - 到我传递一个参照WebView
- 我定义了下面的脚本访问的方法:
#import <WebKit/WebKit.h>
#import <JavaScriptCore/JavaScriptCore.h>
- (void) search:(NSString *)prefix withCallback:(WebScriptObject *)callback;
...其目的是采取两个参数:用于搜索的字符串,以及匿名函数回调来处理结果。它的实现如下:
- (void) search:(NSString *)prefix withCallback:(WebScriptObject *)callback
{
// Functions get passed in as WebScriptObjects, which give you access to the function as a JSObject
JSObjectRef ref = [callback JSObject];
// Through WebView, you can get to the JS globalContext
JSContextRef ctx = [[view mainFrame] globalContext];
// In my case, I have a JSON string I want to pass back into the page as a JavaScript object
JSValueRef obj = JSValueMakeFromJSONString(ctx, JSStringCreateWithCFString((__bridge CFStringRef)responseString));
// And here's where I call the callback and pass in the JS object
JSObjectCallAsFunction(ctx, ref, NULL, 1, &obj, NULL);
}
这实际上是异步通过Objective-C块,但要点在上面。希望它可以帮助别人!
谢谢;这绝对帮助了我! – tenfour 2014-10-29 12:28:47