0

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?

2 Answers 2

1

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

0

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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.