SDK:MacOS 14.0
Xcode:15.0
我搜索了很多答案,但都不适用于我的申请.我无法访问文件夹下的文件内容.
首先,我在App SandBox中配置了权限:
然后我在SwiftUI中使用fileImporter
来允许用户 Select 文件夹:
Button("open file")
.fileImporter(
isPresented: $indexModel.openFileImporter,
allowedContentTypes: [.movie, .avi, .mpeg4Movie, .directory],
allowsMultipleSelection: true
) { results in
do {
let selection = try results.get()
try self.openSelectedPath(selection)
} catch let err {
indexModel.errorMsg = err.localizedDescription
indexModel.showError = true
}
}
在openSelectedPath
中,我通过FileManager
访问文件夹下的内容:
if selection.hasDirectoryPath {
let files = try FileManager.default.contentsOfDirectory(
at: selection,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles]
)
files.enumerated().filter { _, file in
// try grant access here but all fails
guard file.startAccessingSecurityScopedResource() else {
print("\(file.lastPathComponent) cannot access")
return false
}
let isMKV = file.pathExtension.compare("mkv", options: .caseInsensitive, range: nil, locale: nil) == .orderedSame
return file.isFileURL && (isMKV || file.contains(.movie) || file.contains(.avi) || file.contains(.mpeg4Movie))
}
return
}
因此,该文件夹中的所有文件都无法访问.(file.startAccessingSecurityScopedResource
返回假)