I have a webpage loaded in a UIWebView, and a javascript function of the page needs to data from native iOs app, a NSString. How can a Js function access the data in native app
You can execute JavaScript in your UIWebView from Obj-C. Simply call [webView stringByEvaluatingJavaScriptFromString:@"myJavaScript"];
.
I could imagine a setup like this:
Webpage
<html>
<head>
<script type="text/javascript">
function callmeFromObjC(para1) {
// do something
alert(para1);
}
</script>
</head>
<body>
</body>
</html>
Objective-C
NSString *myParameter = @"myParameter";
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"callmeFromObjC('%@')", myParameter]];
I created an iOS/JS library to help make this easier -- that is, communication in both directions using similar methods. You can check it out here: https://github.com/tcoulter/jockeyjs
Sample code for this is available here,you can check it....very usefull
http://ramkulkarni.com/blog/framework-for-interacting-with-embedded-webview-in-ios-application/
Let the javascript load a custom URL, which your app intercepts. It than can parse it, prepare the data and pass it on to your webpage via stringByEvaluatingJavaScriptFromString:
.
With WebViewJavaScriptBridge you can achieve two way communication between javaScript and iOS.
Check this link below for WebViewJavaScriptBridge .
I used this bridge for one of my application for communication between iOS and JS and also vice versa.
https://github.com/marcuswestin/WebViewJavascriptBridge.
[webView loadHTMLString:@"<script src=\"filename.js\"></script>"
baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"function(parameter)"];
Give feedback to iOS
window.location = customprefix://function/parameter=value
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[URL scheme] isEqualToString:@"customprefix"]) {
// handle function name and paramters
}
}
I also wrote a guide on how to call and handle different javascript functions from within iOS. http://www.dplusmpage.com/2012/07/20/execute-javascript-on-ios/