UIWebView用于在Safari中打开URL,但不是以#开头的URL

时间:2012-09-11 14:38:22

标签: iphone objective-c ios

我尝试使用下面的代码在Safari中的HTML5应用中打开链接。但是,代码也在Safari中打开了#links,用于在应用程序内进行内部导航。链接是否前缀为HTTP,导致它们在Safari中打开?如果是这样,我怎么能修改这个脚本来排除它们呢?

感谢。

供参考

请在此处查看GIT回购:https://github.com/philhudson91/flaming-cyril

或者我可以编写它来阻止我正在托管的域名中的链接打开吗?

更新

这是我现在使用的代码......

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
NSURL *requestURL =[ [ request URL ] retain ];
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"#"] invertedSet];
if ([ [ requestURL scheme ] isEqualToString: @"http" ]) NSLog(@"HTTP"); if ([ [ requestURL scheme ] isEqualToString: @"https" ]) NSLog(@"HTTPS"); if (( [ [requestURL absoluteString] rangeOfCharacterFromSet:set].location == NSNotFound )) NSLog(@"Not Local"); if (( [ [ requestURL scheme ] isEqualToString: @"mailto" ])
    && ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) {
    return ![ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ];
}
[ requestURL release ];
return YES; 
}

2 个答案:

答案 0 :(得分:2)

您可以尝试以下操作:(我还没有测试过,这只是在请求方案为http或https时验证URL不包含'#')

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
  NSURL *requestURL =[ [ request URL ] retain ];
  NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"#"] invertedSet];

  NSLog([requestURL absoluteString]);

  if ( ((( ([ [ requestURL scheme ] isEqualToString: @"http" ]) || 
           ([ [ requestURL scheme ] isEqualToString: @"https" ])) && 
         ( [ [requestURL absoluteString] rangeOfCharacterFromSet:set].location != NSNotFound ) ) || 
        ( [ [ requestURL scheme ] isEqualToString: @"mailto" ]) ) && 
      ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) {
      return ![ [ UIApplication sharedApplication ] openURL: [ requestURL autorelease ] ];
  }
  [ requestURL release ];
  return YES; 
}

答案 1 :(得分:1)

以前的答案很好,但似乎检查太多了。我宁愿使用类似的东西:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    NSString *urlString = request.URL.absoluteString;

    if (([urlString rangeOfString:@"http://m.bu-news.com"].location != NSNotFound)) {
        return YES;
    }
    [[UIApplication sharedApplication] openURL:request.URL];
    return NO;
}

它应该足够了。

更新:检查了您的代码并进行了一些测试。上面的代码按预期工作:所有导航链接在应用内打开,所有“阅读全文”链接在Safari中打开。但是没有检查所有链接,可能还存在一些问题。