Let's say I have a UIWebView with some javascript functions. I want those javascript functions to be able to request information from my app and my app should return it. I am able to get the requests using URL Schemes however, I don't know how to return the information back to the javascript function.
Is injecting a javascript variable into the UIWebView, then calling the javascript function again with the variable as a parameter the best way to do it? Or are there methods I can use for UIWebView?
Use asynchronous communication. Have a Javascript function for the Objective C routine to call back into the Javascript with any reply parameters required. The Javascript callback function can even be one of the parameters sent to Objective C code via a URL scheme.
Injecting Javascript via stringByEvaluatingJavaScriptFromString
is absolutely fine.
The other direction would be better handled via webView:shouldStartLoadWithRequest:navigationType:
How to Properly Call ObjectiveC From Javascript (incl. Callback to JS) describes it in detail, sources are included.
Sample JS-code which makes use of the Objective-C returnValue:
NativeBridge.call("objCMethod", ["firstArgument"], function (returnValue) {
if (returnValue) {
// whatever
} else {
// whatever
}
});
-(BOOL)objCMethod:(NSString *)myString { //Do stuff... return YES; }
. Then in the javascript, returnValue
will have the value "YES" right - Ali Hamze 2012-04-05 19:53
-(BOOL)objCMethod:(NSString *)myString
. But there's actually more code involved. In that sample project (http://blog.techno-barje.fr/public/iphone-sdk/NativeBridge/NativeBridge-non-buggy.zip) take a look at webView shouldStartLoadWithRequest
, handleCall
and returnResult
- Andy Friese 2012-04-05 20:15