OGeek|极客世界-中国程序员成长平台

标题: ios - 使用 webView ios 显示下载的 PDF 文件 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:56
标题: ios - 使用 webView ios 显示下载的 PDF 文件

我正在制作一个 iPhone 应用程序,它将下载 PDF 文件并将其显示在 webView 中。 但是我的脚本不会显示下载的 PDF。它确实会下载并保存在 Documents 中,但 webView 不会显示它。

这是我的脚本:

NSString *path = [[NSBundle mainBundle] pathForResource"3" ofType"pdf"];
NSURL *urlen = [NSURL fileURLWithPath:path];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:urlen];
[webView loadRequest:urlRequest];
[webView setScalesPageToFit:YES];



Best Answer-推荐答案


来自NSURL的官方文档official documentation on NSURL .

nil 作为参数发送到 fileURLWithPath: 会产生异常。

问题实际上出在 [[NSBundle mainBundle] pathForResourcefType:] 上。这将返回 nil,而不是文件的实际路径。

这里的问题实际上是 [NSBundle mainBundle] 指的是与您的应用程序捆绑在一起的文件。您需要查看应用的文档目录,该目录存储已下载的文件。

此方法将为您提供应用文档目录的路径:

NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

现在,只需将文件名附加到此路径:

NSString *pdfPath = [documentsPath stringByAppendingPathComponent"3.pdf"];

为了更好地衡量(因为崩溃总是不好的),请确保文件存在:

BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pdfPath];

然后这样结束:

if (fileExists) {
    NSURL *urlen = [NSURL fileURLWithPath:pdfPath];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:urlen];
    [webView loadRequest:urlRequest];
    [webView setScalesPageToFit:YES];
} else {
    // probably let the user know there's some sort of problem
}

关于ios - 使用 webView ios 显示下载的 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23727299/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4