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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With