Nikhil Viradiya
Nikhil Viradiya

Reputation: 85

Sorting files and folder in Document Directory according to Size in Swift iOS

I've been trying to sort my files and folders stored in my document directory according to Size. I sorted my files w.r.t Date with the help of URLResourceKey and properties and tried to use the same Code for Size.

But as the Size is in Int format , comparison can't be made by the following code!

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
    }

Please Help

Upvotes: 1

Views: 1442

Answers (1)

Kamran
Kamran

Reputation: 15248

Inside the do-catch block, you can get the size and return in ascending or descending order as below,

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

Upvotes: 1

Related Questions