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

store internally a PDF from internet and display into WebView

我正在使用 Xcode 6.1.1

为 iOS 8.1 开发应用程序

我想从互联网上下载一个 PDF,存储到我的 iPad 中,然后将其加载到网络视图中;这是 PDF 测试:

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

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

// 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:] or NSSearchPathForDirectoriesInDomains 了解如何获取用户文档文件夹的路径。