ric*_*ick 4 nsfilemanager swift
如何获取URL中文件的URL?
我试过这些:
directoryContents = try FileManager.default.contentsOfDirectory(at: aURL, includingPropertiesForKeys: [URLResourceKey.isRegularFileKey], options: [])
Run Code Online (Sandbox Code Playgroud)
和
...contentsOfDirectory(at: aURL, includingPropertiesForKeys: nil, options: []).filter{ $0.isFileURL })
Run Code Online (Sandbox Code Playgroud)
两个结果都等于
...contentsOfDirectory(at: aURL, includingPropertiesForKeys: nil, options: [])
Run Code Online (Sandbox Code Playgroud)
返回文件和文件夹列表,它获得没有任何过滤器和选项的列表.
此外,我试图只获取目录URLResourceKey.isDirectoryKey,但它没有工作.
如何获取没有目录的文件的URL?
includingPropertiesForKeys 为了性能原因,在遍历目录时从url检索指定键的信息,它不是过滤器标准.
您必须filter通过isDirectory值显式显示结果
let directoryContents = try FileManager.default.contentsOfDirectory(at: aURL, includingPropertiesForKeys: [.isDirectoryKey])
let filesOnly = directoryContents.filter { (url) -> Bool in
do {
let resourceValues = try url.resourceValues(forKeys: [.isDirectoryKey])
return !resourceValues.isDirectory!
} catch { return false }
}
print(filesOnly.count)
Run Code Online (Sandbox Code Playgroud)
或者在macOS 10.11 +,iOS 9.0+中使用 hasDirectoryPath
let directoryContents = try FileManager.default.contentsOfDirectory(at: aURL, includingPropertiesForKeys: nil)
let filesOnly = directoryContents.filter { !$0.hasDirectoryPath }
print(filesOnly.count)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
633 次 |
| 最近记录: |