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?

2 Answers 2

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
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

I already have this part working. My question was, how to return information to the javascript function. Sorry if I wasn't clear enough.
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?
There could be a method like -(BOOL)objCMethod:(NSString *)myString. But there's actually more code involved. In that sample project (blog.techno-barje.fr/public/iphone-sdk/NativeBridge/…) take a look at webView shouldStartLoadWithRequest, handleCall and returnResult.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.