Parse url so that only maps links open in external

2019-09-19 06:50发布

I have web content inside a UIWebView in my app. My goal is to have all links open normally inside the app, but any links starting with "http://maps", get opened in safari, so they can in turn be opened in the external iphone maps app. If you have a solution for this problem stop reading now, below I'm going to propose my solution. Currently all links are opened inside the app, so http://maps links open to m.google.com inside the app. The solution I'm thinking of involves this code which uses openURL to open all links in safari:

(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        \[\[UIApplication sharedApplication] openURL:request.URL];
        return false;
    }
    return true;
}

Obviously the problem with this code is that all links are opened in safari, and I only want map links. Can you suggest a way to parse through links and only pass ones that start with http://maps through the function? Also a more simple question, how do I delegate UIWebView so I can run this code, and also is the viewcontroller.m the right place to put this code?

If you guys could suggest an entire function, including the openURL part above and the link parsing to make sure only maps links get passed through the function that would be awesome. Again, if you have another solution or workaround I would love to hear it. Thanks so much for your help, stackoverflow has been a lifesaver, I'm almost finished with my first project ever!

2条回答
小情绪 Triste *
2楼-- · 2019-09-19 07:14
 NSString *linkPath = [[request url] path];
 if ([linkPath hasPrefix:@""http://maps"]) {

    //open in safari

 }
 else {
  //do whatever

 }
查看更多
3楼-- · 2019-09-19 07:22

Try something like this:

-(BOOL)webView:(UIWebView *)inWeb
shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)inType {
  // let UIWebView deal with non-click requests
  if (inType != UIWebViewNavigationTypeLinkClicked) {
    return YES;
  }

  // URL starts with "http://maps"?
  if ([[request.URL description] hasPrefix:@"http://maps"]) {
    // open URL in Safari and return NO to prevent UIWebView from load it
    [[UIApplication sharedApplication] openURL:[request URL]];
    return NO;
  }

  // otherwise let UIWebView deal with the request
  return YES;
}
查看更多
登录 后发表回答