Tuesday, February 2, 2010

Mapping UIWebview links to controller/delegate actions

In an iPhone application I'm developing, there are some views that are quite complex to code... and I find them much easier to code in HTML/CSS. Since the Webkit engine available on the iPhone is quite powerful, I find it a much easier way to create complex views...

Now if you want this view to interact with your application it is a bit tricky... but not THAT much. Here is a piece of code I have in my controller... well in my UIWebViewDelegate.

// Map links starting with file://
//            ending with #action
// with the action of the controller if it exists.
//
// Open other links in Safari.
- (BOOL)webView: (UIWebView*)webView shouldStartLoadWithRequest: (NSURLRequest*)request navigationType: (UIWebViewNavigationType)navigationType {
 NSString *fragment, *scheme;
 
 if (navigationType == UIWebViewNavigationTypeLinkClicked) {
  [webView stopLoading];
  fragment = [[request URL] fragment];
  scheme = [[request URL] scheme];

  if ([scheme isEqualToString: @"file"] && [self respondsToSelector: NSSelectorFromString(fragment)]) {
   [self performSelector: NSSelectorFromString(fragment)];
   return NO;
  }
  
  [[UIApplication sharedApplication] openURL: [request URL]];
 }

 return YES;
}

Basically we catch the click on a link, and if the link is of the form file://...#action we then look for the selector action in the controller and trigger it if it exists.

It's THAT simple. :)

0 comments:

Post a Comment