ios - 如何在 html 文件上链接本地 pdf 文件 - html 文件显示在 UIWebView

标签 ios uiwebview

我正在使用以下代码在我的 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 View 中加载 pdf。

我想使用 UIWebView 委托(delegate)将 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; 
    }
}

最佳答案

您应该更清楚地说明您希望 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 中加载链接来工作。不包含超文本类型协议(protocol)前缀 (http://)。

提示:确保您已为 UIWebView 设置了代理。在 viewDidLoad方法。
- (void)viewDidLoad
{
    [super viewDidLoad];

    webView.delegate = self;
}

关于ios - 如何在 html 文件上链接本地 pdf 文件 - html 文件显示在 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10549149/

相关文章:

ios - 上传 PFFile 和 PFObject 的区别

ios - UITableViewCell 中的长宽比 NSLayoutConstraint 中断

ios - 在 ios 的 UIWebview 中调用 javaScript

iphone - UIDocumentsInteractionController 显示 iBooks 但不打开它

ios - Facebook 不返回电子邮件

ios - 当我截图时 PHPhotoLibraryChangeObserver 不起作用

javascript - 使用按钮在 iOS webview 中模拟点击

iphone - 将 UIWebView 中的图像大小调整为视口(viewport)大小

ios - 将数据传入和传出嵌入式 UIWebView

iPhone-UIWebView : Detect User Scrolling to Bottom of Page