gpt4 book ai didi

ios - 根据 Swift iOS 中的大小对文档目录中的文件和文件夹进行排序

转载 作者:行者123 更新时间:2023-11-28 05:44:20 24 4
gpt4 key购买 nike

我一直在尝试根据大小 对存储在文档目录中的文件和文件夹进行排序。我在 URLResourceKey 和属性的帮助下对我的文件 w.r.t Date 进行了排序,并尝试对大小使用相同的代码。

但是由于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 block 中,您可以获得 size 并以 ascendingdescending 顺序返回如下所示,

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)
}

关于ios - 根据 Swift iOS 中的大小对文档目录中的文件和文件夹进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55448770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com