How do I return information to javascript function in Objective-C?

Go To StackoverFlow.com

1

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?

2012-04-05 18:39
by Ali Hamze


0

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.

2012-04-05 19:59
by hotpaw2


2

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
    }
});
2012-04-05 18:53
by Andy Friese
I already have this part working. My question was, how to return information to the javascript function. Sorry if I wasn't clear enough - Ali Hamze 2012-04-05 19:15
On the Objective C side of the code, how do I return the value to the script you posted? Can I just use the regular return key? For example: -(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
There could be a method like -(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
Ads