0

I'm trying to get the total file size of my documentDirectory, but the fileSize attribute is not giving me the correct value. I then tried getting the fileSize attribute of all the folders inside the documentDirectory, apparently all the folders are the same size.

With both of those attempts failing, I've decided to try get the value of every file (not folder) inside the documentDirectory, hence needing to iterate through each folder, to find the files.

Folder structure

documentDirectory
  -folder
    -file
    -file
    -file
    -folder
       -file
       -file
  -folder
    -file
    -file

My current code, to get the list of files in the documentDirectory is below, I can't work out how to get this code to work as I want it to.

Current code

let fileManager = FileManager.default
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: AnyObject = paths[0]

do {
    let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentsDirectory)")
    for fileName in fileNames {
        //do things with the file
    }
} catch {
    print(error)
}

Edit: Here is the code I was using to try get the size of the documentDirectory

let fileManager = FileManager.default
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: AnyObject = paths[0]
var fileSize : UInt64 = 0

do {
    let attr : NSDirectory? = try fileManager.attributesOfItem(atPath: documentsDirectory as! String)

    if attr != nil {
        fileSize = attr!.fileSize()
    }

} catch {
    print(error)
}
Gary Kenyon
  • 368
  • 1
  • 6
  • 20
  • 1
    See this to get *all* files in a directory: http://stackoverflow.com/a/30540587/2227743 – Eric Aya Jul 13 '16 at 09:48
  • 1
    [Here's a thorough answer](http://stackoverflow.com/questions/2188469/calculate-the-size-of-a-folder/28660040#28660040) with code that calculates the size of a folder on disk. – Nikolai Ruhe Jul 13 '16 at 09:51
  • Eric, the link you posted brings up an error: Nil is not compatible with expected argument type: 'FileManager.DirectoryEnumerationOptions'. When I replace it with the suggested argument type, I get all kinds of erroes. – Gary Kenyon Jul 13 '16 at 10:19
  • @GaryKenyon Use `[]` for passing no options instead of nil. The answer was for Swift 1, this part has changed. – Eric Aya Jul 14 '16 at 15:28

0 Answers0