我一直在尝试根据大小对存储在我的文档目录中的文件和文件夹进行排序。我在URLResourceKey和属性的帮助下对w.r.t Date文件进行了排序,并尝试使用相同的Code for Size。
但由于Size是Int格式,因此无法通过以下代码进行比较!
func filesSortedListDate(atPath: URL) -> [String]?
{
var fileNames = [String]()
let keys = [URLResourceKey.contentModificationDateKey]
guard let fullPaths = try? FileManager.default.contentsOfDirectory(at: atPath, includingPropertiesForKeys:keys, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles) else
{
return [""]
}
let orderedFullPaths = fullPaths.sorted(by: { (url1: URL, url2: URL) -> Bool in
do {
let values1 = try url1.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
let values2 = try url2.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
if let date1 = values1.creationDate, let date2 = values2.creationDate {
return date1.compare(date2) == ComparisonResult.orderedDescending
}
} catch _{
}
return true
})
for fileName in orderedFullPaths
{
do {
let values = try fileName.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
if let date = values.creationDate{
//let date : Date? = values.contentModificationDate
print(fileName)
let theFileName = fileName.lastPathComponent
fileNames.append(theFileName)
}
}
catch _{
}
}
return fileNames
}
请帮忙
在do-catch
区块内,您可以获得size
并以ascending
或descending
顺序返回,如下所示,
do {
let size1 = try url1?.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
let size2 = try url2?.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
return size1 > size2
} catch {
print(error.localizedDescription)
}