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
1 Answer
Reset to default 1You 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
版权声明:本文标题:swift - Directory access can't access subfolders - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741558383a2385296.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论