文件、文件夹操作(I)

时间:2022-08-11 07:22:00

遍历一个目录下的所有文件

首先我们获取用户文档目录路径

 let manager = FileManager.default
let urlForDocument = manager.urls(for: .documentDirectory, in:.userDomainMask)
let url = urlForDocument[] as URL
print("---------->\(url)")

打印结果:

---------->file:///Users/huanggang/Library/Developer/CoreSimulator/Devices/7B9AE7A4-4838-495B-964D-560DF760F7E1/data/Containers/Data/Application/70D8DA8D-4FEF-4715-B82E-0F40C1BC1B78/Documents/

深度遍历,会递归遍历子文件夹

 let enumeratorAtPath = manager.enumerator(atPath: url.path)
enumeratorAtPath?.skipDescendants() //跳过递归到最近获得的子目录
print("enumeratorAtPath: \(enumeratorAtPath?.allObjects)")

打印结果:

enumeratorAtPath: Optional([])

参考:文件夹操作