2

我正在使用以下代码在我的 UiWebView 上显示本地 html 文件。

NSString *path = [[NSBundle mainBundle] pathForResource:@"test.html"];  

NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];    

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];

[_webView loadHTMLString:htmlString baseURL:baseURL];
[_webView setBackgroundColor:[UIColor clearColor]];

应用程序正确显示 html。在 test.html 中有一个指向本地 pdf 文件 hello.pdf 的链接。此 pdf 已添加到项目中。但是当我点击链接时,什么也没有发生。当用户单击链接时,我想在我的 Web 视图中加载 pdf。

我想使用 UIWebView 委托将 Internet 超链接(例如http://www.google.com)请求发送到 safari 应用程序。

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType 
{
    NSLog(@"%@",inRequest.URL.absoluteString);
    if([inRequest.URL.absoluteString rangeOfString:@"hello.pdf"].location == NSNotFound)
    {
        if ( inType == UIWebViewNavigationTypeLinkClicked ) 
        {
            [[UIApplication sharedApplication] openURL:[inRequest URL]];
            return NO;
        }
        return YES;
    }
    else
    {
       return NO; 
    }
}
4

1 回答 1

0

您应该更清楚地说明您希望 Internet 超链接在 Safari 中加载,而本地超链接在您的UIWebView.

我刚刚对此进行了测试,它可以满足您的要求:

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType 
{
    if (inType == UIWebViewNavigationTypeLinkClicked) {
        if ([inRequest.URL.absoluteString rangeOfString:@"http://"].location == NSNotFound) {
            return YES;
        }
        else {
            [[UIApplication sharedApplication] openURL:[inRequest URL]];
            return NO;
        }
    }
    else {
        return YES;
    }
}

这仅通过加载UIWebView不包含超文本类型协议前缀 (http://) 的链接来工作。

提示:确保您已UIWebViewviewDidLoad方法中设置了委托。

- (void)viewDidLoad
{
    [super viewDidLoad];

    webView.delegate = self;
}
于 2012-05-11T12:36:50.517 回答