Search code examples
iosswiftpdfkit

Path to pdf in directory with pdfKit


I am starting to use PDFKit, with a pdf file located in the root, it works with the following code:

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)
    }
}

But if I change the pdf file inside a directory for example "mydirectory", it does not work, my code is the following:

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

    }
}

Any suggestions to fix the path problem.


UPDATE

According to the suggestion, try the following code, but I can not visualize the PDF either.

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
    }
}

Solution

  • Your code to read the pdf from a subdirectory is correct and as I read they get a nil in the path, that's for sure because your container folder has not been created correctly. You can see yellow and blue folder, your container folder should be blue.

    To make blue folder you should do following steps:

    • Prepare folder structure with files in it.
    • Drag that folder into xcode i.e. project navigation pan.
    • Select " Create folder references for any added folders " option.
    • Finally click to add.

    You will get that folder with blue color and your code can read the 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.

    Blue is used to represent a "Folder Reference".