2

我尝试使用下面的代码在 Safari 中打开我的 HTML5 应用程序中的链接。但是,该代码还在 Safari 中打开了用于应用程序内部导航的 # 链接。链接是否以 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; 
}
4

2 回答 2

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; 
}
于 2012-09-11T15:52:57.960 回答
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 中打开。但是没有检查所有链接,可能仍然存在一些问题。

于 2012-10-06T11:03:14.503 回答