2

I have an IOS application which has a web browser in it.

When this web browser is displayed, it navigates to a page on Internet, say http://myexample.com/myiosapp.

Is it possible to place a javascript code on this web site, which, when downloaded to phone, communicates with the native application? Can it call an Objective-C method, or write something to storage space of this application?

Ex. Code hosted on myexample.com/myios app:

function saveSomeString() {
    xcode.Save("somestring");
}

should call an Objective-C function named Save, which saves incoming string parameter to local storage.

4
  • You can use local storage in js it's really simple! See diveintohtml5.info/storage.html Commented Nov 27, 2012 at 14:34
  • But after using local storage, can I read that information by XCode? Commented Nov 27, 2012 at 14:38
  • No. I hadn't understood what you were looking for. Commented Nov 27, 2012 at 14:43
  • @SerhatÖzgel: XCode is a development environment, not a programming language. So it has no methods. You probably mean an Objective-C method. I've changed the title and the tags accordingly. Commented Nov 27, 2012 at 14:51

1 Answer 1

6

Yes, you can, but it is a bit hacky.

On the Objective-C side:

Basically, in the UIWebView, you will use method shouldStartLoadWithRequest (from the UIWebViewDelegate) which is called before a URL request starts:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

On Javascript side:

Your javascript code will navigate to a 'fake' URL that you will filter on the method above. Something like:

window.location = "js2objc://save:param";

Back on the Objective-C side:

Inside the method I mentioned earlier, you look for the keyword js2objc (or whichever you choose) and then extract the info and take any appropriate action:

if([[url scheme] isEqualToString:@"js2objc"]){
    // extract the parameters and save them, o do whatever action you need
    return NO;  // so the UIWebView doesn't actually follow the url
}
Sign up to request clarification or add additional context in comments.

2 Comments

This should do the trick, thanks. I'll accept it once I try it.
I found a tutorial that describes the above step-by-step. blog.techno-barje.fr/post/2010/10/06/…

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.