开发者

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 applica开发者_运维百科tion 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


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.


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


I just created a library that will facilitate this communication for you largely using the method described by mvds and Ondrej. Includes two-way communication, jQuery event-style, with optional JSON payloads with multiple listeners. Check it out: https://github.com/tcoulter/jockeyjs


Maybe by changing the url hash?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜