ios - 使用 pdfKit 的目录中 pdf 的路径

标签 ios swift pdfkit

我开始使用 PDFKit,在根目录中有一个 pdf 文件,它使用以下代码:

if let path = Bundle.main.path(forResource: "mypdf1", ofType: "pdf") {
    let url = URL(fileURLWithPath: path)
    if let pdfDocument = PDFDocument(url: url) {
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .vertical
        pdfView.document = pdfDocument
        print(path)
    }
}

但是如果我更改目录中的 pdf 文件,例如“mydirectory”,它不起作用,我的代码如下:

if let path = Bundle.main.path(forResource: "mypdf1", ofType: "pdf", inDirectory: "mydirectory") {
    let url = URL(fileURLWithPath: path)
    if let pdfDocument = PDFDocument(url: url) {
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .vertical
        pdfView.document = pdfDocument

    }
}

解决路径问题的任何建议。


更新

按照建议,尝试了下面的代码,但是我也看不到PDF。

if let documentURL = Bundle.main.url(forResource: "mypdf1", withExtension: "pdf", subdirectory: "mydirectory") {
    if let document = PDFDocument(url: documentURL) {
        pdfView.autoScales = true
        pdfView.backgroundColor = UIColor.lightGray
        pdfView.document = document
    }
}

最佳答案

您从子目录读取 pdf 的代码是正确的,当我读到它们在路径中得到一个 nil 时,这是肯定的,因为您的容器文件夹没有正确创建。您可以看到黄色和蓝色文件夹,您的容器文件夹应该是蓝色的。

要制作蓝色文件夹,您应该执行以下步骤:

  • 准备包含文件的文件夹结构。
  • 将该文件夹拖到 xcode 中,即项目导航面板。
  • 选择“为任何添加的文件夹创建文件夹引用”选项。
  • 最后点击添加。

您将获得蓝色文件夹,您的代码可以读取 pdf。

There are two types of folders in Xcode: groups and folder references. You can use groups to organize files in your project without affecting their structure on the actual file system. This is great for code, because you’re only going to be working with your code in Xcode. On the other hand, groups aren’t very good for resource files.

On any reasonably complicated project, you’ll usually be dealing with dozens – if not hundreds – of asset files, and those assets will need to be modified and manipulated from outside of Xcode, either by you or a designer. Putting all of your resource files in one flat folder is a recipe for disaster. This is where folder references come in. They allow you to organize your files into folders on your file system and keep that same folder structure in Xcode.

蓝色用于表示“文件夹引用”。

关于ios - 使用 pdfKit 的目录中 pdf 的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428411/

相关文章:

ios - 如何为我的自定义 TabBarController 设置自定义 tabBar?

Python - pdfkit 的超时规则

node.js - 在 Node js 中使用 pdfkit 不会更改 PDF 页面大小

python - 将内存html文件传递给pdfkit

ios - 如何在 Swift 中全局声明数据库连接变量

ios - 无法连接 Storyboard Unwind Segue

ios - 从 UIActivityViewController 关闭邮件后 UINavigationBar 消失

ios - 在 awakeFromNib() 上 - 错误实例成员 'button' 不能在类型 'CustomView' 上使用

ios - Swift 3 UITapGestureRecognizer 没有收到水龙头

ios - 根据用户的位置检索地理定位图像