Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to list all PDFs inside a folder that is stored in my Xcode project using SwiftUI, but after trying many different methods I found on here I cannot get it working.

Currently I am using file manager to list the items but when I try and print or list the items found it returns nil.

I have added the PDFs by dragging them into the Xcode project. I have also made sure that they are in my Copy Bundle Resource so I can use FileManager. See below:

enter image description here

Here is my Xcode structure, I am trying to list all items inside PDF. As you can see below the PDFs are stored outside the main folder structure in "/Swift/Products/Detail/Tab5/PDF", so when trying to list the files using Bundle.main.bundlePath, it looks at products.app.

enter image description here

Here is the code where I am trying to use FileManager to find all PDFs inside the folder:

struct ProductTab5View: View {
    
    @State var files = getFiles()

    var body: some View {
        VStack{
            ForEach(0..<files.count, id: .self) { item in
                 Text(files[item])
             }
        }
    }
}

func getFiles() -> Array<String>{
    // Get  document directory url
    let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    var files: [String] = []
    
    do {
        // Get the directory contents urls (including subfolders urls)
        let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil)
        print(directoryContents)
        // filter  directory contents:
        let pdfFiles = directoryContents.filter{ $0.pathExtension == "pdf" }
        let pdfFileNames = pdfFiles.map{ $0.deletingPathExtension().lastPathComponent }
        files.append(contentsOf: pdfFileNames)

    } catch {
        print(error)
    }
    return files
}
question from:https://stackoverflow.com/questions/65672098/filemanager-cant-locate-pdf-directory-in-xcode-project

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
155 views
Welcome To Ask or Share your Answers For Others

1 Answer

In such a way resources are copied flat into root application bundle, not user 's Documents as it was tried in provided code snapshot (and no PDF sub-directory is created for you).

So the solution would be just to iterate internal pdf files, like

func getFiles() -> Array<String> {
    return Bundle.main.urls(forResourcesWithExtension: "pdf", subdirectory: nil)?
        .compactMap { $0.lastPathComponent } ?? []
}

Tested with Xcode 12.1 / iOS 14.1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...