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

时间:2019-04-01 05:49:02

标签: ios arrays swift sorting size

我一直在尝试根据大小对存储在文档目录中的文件和文件夹进行排序。我借助URLResourceKey和属性对带有日期的文件进行了排序,并尝试使用相同的“尺寸代码”。

但是由于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
    }

请帮助

1 个答案:

答案 0 :(得分:1)

do-catch块内,您可以获取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)
}