Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suggestions for how to communicate from JS running in a UIWebView to the hosting obj-c app?

I plan to have a shell iphone app with a uiwebview, with the bulk of my application running through javascript in the uiwebview.

Now i know it's easy to communicate from the obj-c environment to the javascript environment by using stringByEvaluatingJavaScriptFromString, however is there a good recommended way of communicating from the javascript environment to the obj-c world?

Thanks

like image 973
Chris Avatar asked Apr 05 '11 22:04

Chris


2 Answers

I always use an approach in which the app "navigates" to a special URL:

window.location = "myapp://somemessage/someargument";

And where the app catches this in the following function:

-(BOOL)webView:(UIWebView *)webView
                shouldStartLoadWithRequest:(NSURLRequest *)request
                navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if ( [[url scheme] isEqualToString:@"myapp"] )
    {
        [self handleJSEvent:url];
        return NO;
    }
    return YES;
}

Furthermore, depending on what you need, you could use some kind of event queue which you fetch using JSON.stringify(events), in response to a message sent to the app using the method described above. For communicating from app to js JSON is also very suitable.

If there is a standard or a standard way to do this, I clearly missed it.

like image 77
mvds Avatar answered Nov 14 '22 22:11

mvds


There is a very nice method to call javascript inside of UIWebView:

[webView stringByEvaluatingJavaScriptFromString:@"yourJSFunction('some_data');"];

call backs are best done as mentioned by MVDS through the Url:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
like image 28
Ondrej Rafaj Avatar answered Nov 14 '22 23:11

Ondrej Rafaj