Reputation: 1376
I'm trying to figure out a way to execute some Javascript and return the result through a completion block, but for some reason, the callback never fires.
+ (void)doSomethingWithCompletionHandler:(void (^)(NSError* error, NSString *result))completionHandler;
{
JSContext __block *context;
context = [[MyJSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];
context[@"done"] = (id) ^(NSString *result)
{
context = nil;
completionHandler(nil, result);
};
// this works
// [context evaluateScript:@"(function(){ done('immediate'); })()"];
// this does not
[context evaluateScript:@"(function(){ setTimeout(function(){ done('delayed'); }, 1000); })()"];
}
As soon as I try to making it async, simulated here by using a timeout, the block in context[@"done"] is never called.
I've extended JSContext to make sure it is not deallocated when it goes out of scope (hence the __black hack).
Am I approaching this the wrong way?
Upvotes: 0
Views: 761
Reputation: 26
I guess the problem is there is no setTimeout function in JavaScriptCore. You can write it yourself or to look for some existed libraries for that like (self promotion!) https://github.com/artemyarulin/JSCoreBom
P.S. It is really good idea to have at least setTimeout, because many-many-many libraries are using that
P.P.S Use JSContext setExceptionHandler in order to catch errors like that
Upvotes: 1
Reputation: 1376
It seems that functions like setTimeout and setInterval is not available in JavaScriptCore, and since the sandboxed nature of it, I assume that I won't be needing any async functions either, so lets just return
and be done with it ;)
Upvotes: 0