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