Skip to content

Instantly share code, notes, and snippets.

@goocarlos
Created January 14, 2015 14:30
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save goocarlos/16c13397ec69f32679d3 to your computer and use it in GitHub Desktop.
Save goocarlos/16c13397ec69f32679d3 to your computer and use it in GitHub Desktop.
folderSize Swift Implementation
class func folderSize(folderPath:String) -> UInt{
// @see http://stackoverflow.com/questions/2188469/calculate-the-size-of-a-folder
let filesArray:[String] = NSFileManager.defaultManager().subpathsOfDirectoryAtPath(folderPath, error: nil)! as [String]
var fileSize:UInt = 0
for fileName in filesArray{
let filePath = folderPath.stringByAppendingPathComponent(fileName)
let fileDictionary:NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: nil)!
fileSize += UInt(fileDictionary.fileSize())
}
return fileSize
}
@aybekckaya
Copy link

Thanks a lot
For Swift 5, and for people who want more than folder size :)

 // MARK: - URLFileAttribute
struct URLFileAttribute {
    private(set) var fileSize: UInt? = nil
    private(set) var creationDate: Date? = nil
    private(set) var modificationDate: Date? = nil

    init(url: URL) {
        let path = url.path
        guard let dictionary: [FileAttributeKey: Any] = try? FileManager.default
                .attributesOfItem(atPath: path) else {
            return
        }

        if dictionary.keys.contains(FileAttributeKey.size),
            let value = dictionary[FileAttributeKey.size] as? UInt {
            self.fileSize = value
        }

        if dictionary.keys.contains(FileAttributeKey.creationDate),
            let value = dictionary[FileAttributeKey.creationDate] as? Date {
            self.creationDate = value
        }

        if dictionary.keys.contains(FileAttributeKey.modificationDate),
            let value = dictionary[FileAttributeKey.modificationDate] as? Date {
            self.modificationDate = value
        }
    }
}

extension URL { 
   public func directoryContents() -> [URL] {
        do {
            let directoryContents = try FileManager.default.contentsOfDirectory(at: self, includingPropertiesForKeys: nil)
            return directoryContents
        } catch let error {
            print("Error: \(error)")
            return []
        }
    }

  public func folderSize() -> UInt {
        let contents = self.directoryContents()
        var totalSize: UInt = 0
        contents.forEach { url in
            let size = url.fileSize()
            totalSize += size
        }
        return totalSize
    }

    public func fileSize() -> UInt {
        let attributes = URLFileAttribute(url: self)
        return attributes.fileSize ?? 0
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment