5

Is it possible to run some javascript code (having perhaps an NSString as input) without using a UIWebView? I would like to run this code in a separate thread so UIWebView is not possible and I don't really want to render anything, just get back the results.

3 Answers 3

3

I have not tried this, but here is one idea:

Write code to allocate an empty UIWebView but doesn't add it as a subview anywhere, and just directly call - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script on your javascript.

Then use NSOperation to run that in parallel.

Any reason that might not work for you? I think it would avoid displaying anything for the UIWebView.

As a side note, I can't think of anything you can do in javascript that you can't do more quickly directly in Objective-C. Except maybe parsing javascript that you get externally, which may be considered a no-no by Apple, depending on the details.

Guessing at your goals: If you want to parse a JSON server reply, I recommend the json-framework library hosted on google code. It has a nice interface, and it is surprisingly easy to learn and integrate.

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't seem to work, for every UIWebView method I try to call I get "bool _WebTryThreadLock(bool), 0xf42930: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now..." As for my reasons, I'm mostly experimenting :)
Unless explicitly documented, it's not safe to call ANY method other than retain* on a UIKit object. So I wouldn't expect this to ever work.
*technically release is thread-safe by itself, but if you are the last person to release an object, it may cause dealloc to be run on your thread, which is not always safe.
1

I think Parmanoir's article Taming JavascriptCore within and without WebView may give you some advice.

1 Comment

JavaScriptCore is not exposed in the SDK (WebKit is a private framework) but the link is very interesting, thanks!
-1
 self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(getResults:) userInfo:nil repeats:YES];

-(void)getResults
{
    NSString *value = [self.webView stringByEvaluatingJavaScriptFromString:@"javascript"];
}   

Any reason you couldn't just do something like this. Shouldn't be that big of an overhead on your main thread.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.