Parse url so that only maps links open in external app from within UIWebView?

≡放荡痞女 提交于 2019-12-13 05:12:35

问题


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!


回答1:


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;
}



回答2:


 NSString *linkPath = [[request url] path];
 if ([linkPath hasPrefix:@""http://maps"]) {

    //open in safari

 }
 else {
  //do whatever

 }


来源:https://stackoverflow.com/questions/7679841/parse-url-so-that-only-maps-links-open-in-external-app-from-within-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!