ios - 在内部存储来自互联网的 PDF 并显示到 WebView

标签 ios objective-c pdf uiwebview

我正在使用 Xcode 6.1.1 开发适用于 iOS 8.1 的应用

我想从互联网下载 PDF,存储到我的 iPad 中,然后将其加载到 WebView 中;这是 PDF 测试:

pdf screenshot

这是我尝试在 WebView 上显示后在 iPad 上得到的结果:

iPad screenshot

这是我到目前为止的代码...

// Get the PDF Data from the url in a NSData Object
    NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.ferc.gov/docs-filing/elibrary/larg-file.pdf"]];

    // Store the Data locally as PDF File
    NSArray *searchPaths            = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentFolderPath    = searchPaths[0];
    NSString *archivePath           = [documentFolderPath stringByAppendingPathComponent:@"larg-file.pdf"];

    [pdfData writeToFile:archivePath atomically:YES];

    // Now create Request for the file that was saved in your documents folder
    NSURL *url = [NSURL fileURLWithPath:archivePath];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [_webView setUserInteractionEnabled:YES];
    [_webView setDelegate:self];
    [_webView loadRequest:requestObj];

我该如何完成这项工作?

编辑:这就是答案

NSArray *searchPaths            = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentFolderPath    = searchPaths[0];
    NSString *archivePath           = [documentFolderPath stringByAppendingPathComponent:@"larg-file.pdf"];

    if (![Functions isAlreadyStoredinDeviceFileWithName:@"larg-file.pdf"]) {

        NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.ferc.gov/docs-filing/elibrary/larg-file.pdf"]];
        [pdfData writeToFile:archivePath atomically:YES];
    }


    // Now create Request for the file that was saved in your documents folder
    NSURL *url                  = [NSURL fileURLWithPath:archivePath];
    NSURLRequest *requestObj    = [NSURLRequest requestWithURL:url];

    [_webView setUserInteractionEnabled:YES];
    [_webView setDelegate:self];
    [_webView loadRequest:requestObj];

最佳答案

这段代码:

NSString *resourceDocPath = [[NSString alloc] initWithString:[
    [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
    stringByAppendingPathComponent:@"Documents"]];

尝试在应用程序包中构建一个目录。您没有应用程序包的写入权限。因此,您的文件未保存。

查看 -[NSFileManager URLsForDirectory:inDomains:]NSSearchPathForDirectoriesInDomains了解如何获取用户文档文件夹的路径。

关于ios - 在内部存储来自互联网的 PDF 并显示到 WebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27830670/

相关文章:

ios - PickerView - 如何根据分段控件选择返回 2 个不同的数组

java - 如果 HTML 包含特殊/非法字符,从 Html 创建 IText Pdf 将失败

ios - AutoResizingView 内部的 AutoLayout

c# - iTextSharp ShowTextAligned anchor

sql-server - 包含 1.5 亿页的 100,000 个 PDF 的文本索引

ios - 在 iOS 上的网页上使用键盘打开方向更改的缩放问题

ios - 如何重命名 Storyboard并保留其他 Storyboard的链接

objective-c - SBTableAlert 崩溃

iphone - NSSortDescriptor - 顺序改变了吗?

objective-c - 在自定义框架中添加自定义框架