3

In a native iPhone app, I use a UIWebView to load a web page.

I want to use JavaScript in the web page to communicate back with the Objective-C code, for example invoke a function in Objective-C code.

Is there any way to implement this?

1
  • take a look at phonegap, they use the url to communicate Commented Dec 23, 2010 at 7:55

1 Answer 1

8

There is no "direct" way to do this, but you could utilize the UIWebViewDelegate and trap a link with a custom scheme, so in your markup, you'd write something like this:

<a href="myapp://app_action?doSomething">Do Something</a>

Then, in your UIWebViewDelegate's -webView:shouldStartLoadWithRequest:navigationType: method, write something like this:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if([[[request URL] scheme] isEqualToString:@"myapp"]) { 
       SEL selector = NSSelectorFromString([[request URL] query]);
       if([self respondsToSelector:selector]) {
          [self performSelector:selector];
       } else {
          //alert user of invalid URL
       }
       return NO;
    }
    return YES;
}
Sign up to request clarification or add additional context in comments.

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.