admin管理员组

文章数量:1292658

I am writing a Swift program where I need to transverse a directory tree looking for files. I am using a fileimporter to get the root directory.

The code of my function is as follows. I can access the root directory but as soon as I go to process a subdirectory I don't have permission to it.

Here is my code:

func processDir(startDir: URL) -> () {
    do {
        if CFURLStartAccessingSecurityScopedResource(startDir as CFURL) {
            let currentContents: [URL] = try manager.contentsOfDirectory(at: startDir, includingPropertiesForKeys: nil)
            
            for entry in currentContents {
                if entry.hasDirectoryPath {
                    processDir(startDir: entry)
                } else {
                    // it's a file
                    print(entry)
                }
            }
        }
    } catch {

I am writing a Swift program where I need to transverse a directory tree looking for files. I am using a fileimporter to get the root directory.

The code of my function is as follows. I can access the root directory but as soon as I go to process a subdirectory I don't have permission to it.

Here is my code:

func processDir(startDir: URL) -> () {
    do {
        if CFURLStartAccessingSecurityScopedResource(startDir as CFURL) {
            let currentContents: [URL] = try manager.contentsOfDirectory(at: startDir, includingPropertiesForKeys: nil)
            
            for entry in currentContents {
                if entry.hasDirectoryPath {
                    processDir(startDir: entry)
                } else {
                    // it's a file
                    print(entry)
                }
            }
        }
    } catch {
Share Improve this question edited Feb 14 at 8:30 mahal tertin 3,41425 silver badges43 bronze badges asked Feb 13 at 7:29 tbirgtbirg 111 silver badge1 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 1

You should not call CFURLStartAccessingSecurityScopedResource on every directory you find. You should only call it once on the URL you got from fileImporter.

I would move the call to the caller of processDir.

.fileImporter(isPresented: $isPresented, allowedContentTypes: [.directory]) { result in
    do {
        let url = try result.get()
        if url.startAccessingSecurityScopedResource() {
            defer { url.stopAccessingSecurityScopedResource() }
            processDir(startDir: url)
        }
    } catch {
        print(error)
    }
}
func processDir(startDir: URL) -> () {
    do {
        let currentContents: [URL] = try FileManager.default.contentsOfDirectory(at: startDir, includingPropertiesForKeys: nil)
        for entry in currentContents {
            if entry.hasDirectoryPath {
                processDir(startDir: entry)
            } else {
                print(entry)
            }
        }
    } catch {
    }
}

本文标签: swiftDirectory access can39t access subfoldersStack Overflow