我正在使用XCode 8.2制作一个应用程序,它的运行速度为3.0.2,我正在尝试递归地列出通过itunes与iOS应用程序共享的文件。
目前,以下代码可以工作:
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
print(documentsUrl.absoluteString)
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
print(directoryContents)
} catch let error as NSError {
print(error.localizedDescription)
}但是,contentsOfDirectory定位这里的文档声明该函数只执行对这里的浅层遍历,并建议对该URL执行深度遍历的函数,即枚举器,其文档位于这里。
我使用以下代码片段尝试使用深度遍历列出当前URL下的所有文件:
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
print(documentsUrl.absoluteString)
let dirContents = FileManager.default.enumerator(at: documentsUrl.resolvingSymlinksInPath(), includingPropertiesForKeys: nil, options: [])
print(dirContents.debugDescription)
while let element = dirContents?.nextObject() as? String {
print(element)
}问题是,虽然第一个片段确实显示文件URL,但第二个片段不显示任何内容。
有人能告诉我我能做什么来解决这个问题吗?我非常希望使用第二个片段,而不是使用第一个函数来解决这个问题。
发布于 2016-12-20 07:52:51
FileManager有两种方法可以获得目录枚举数:
第一个返回枚举数,它枚举字符串(文件路径),第二个返回枚举器,它枚举URL。
您的代码使用基于URL的枚举数,因此对as? String的条件转换失败,不会产生任何输出。
您必须将其转换为URL:
if let dirContents = FileManager.default.enumerator(at: documentsUrl.resolvingSymlinksInPath(), includingPropertiesForKeys: nil) {
while let url = dirContents.nextObject() as? URL {
print(url.path)
}
}您还可以使用for-循环来迭代:
if let dirContents = FileManager.default.enumerator(at: documentsUrl.resolvingSymlinksInPath(), includingPropertiesForKeys: nil) {
for case let url as URL in dirContents {
print(url.path)
}
}发布于 2022-05-20 13:03:50
我们可以使用枚举数迭代所有URL,并使用以下方法返回有效的文件URL
func extractFileURLs(from directory: String = "JsonData", withExtension fileExtension: String = "json") -> [URL] {
var jsonFileURLs: [URL] = []
if let enumerator = FileManager.default.enumerator(
at: Bundle.main.bundleURL, // replace url if using another bundle
includingPropertiesForKeys: [.isRegularFileKey],
options: [.skipsHiddenFiles]
) {
for case let fileURL as URL in enumerator where fileURL.pathExtension == fileExtension {
jsonFileURLs.append(fileURL)
}
}
guard !jsonFileURLs.isEmpty else {
assertionFailure("Please verify directory name or file extension")
}
return jsonFileURLs
}https://stackoverflow.com/questions/41236342
复制相似问题