Last active
April 25, 2017 20:10
-
-
Save tylerarnold/b84499638ff7765539c68e4ab2de08aa to your computer and use it in GitHub Desktop.
A method to calculate the accumulated size of a directory on the volume in bytes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Nikolai Ruhe on 2016-02-10. | |
// Copyright (c) 2016 Nikolai Ruhe. All rights reserved. | |
// updated for Swift 3, Tyler Arnold 2017-04-25 | |
// | |
import Foundation | |
extension FileManager { | |
func allocatedSizeOfDirectoryAtURL(directoryURL: URL) throws -> UInt64 { | |
var accumulatedSize = UInt64(0) | |
let prefetchedProperties = [URLResourceKey.isRegularFileKey, URLResourceKey.fileAllocatedSizeKey, URLResourceKey.totalFileAllocatedSizeKey] | |
var errorDidOccur: Error? | |
let errorHandler: (URL, Error) -> Bool = { _, error in | |
errorDidOccur = error | |
return false | |
} | |
if let e = self.enumerator(at: directoryURL, | |
includingPropertiesForKeys: prefetchedProperties, | |
options: FileManager.DirectoryEnumerationOptions(), | |
errorHandler: errorHandler) { | |
let keys: Set<URLResourceKey> = [URLResourceKey.isRegularFileKey, URLResourceKey.totalFileAllocatedSizeKey, URLResourceKey.fileAllocatedSizeKey] | |
for item in e { | |
if let contentItemURL = item as? URL { | |
if let error = errorDidOccur { throw error } | |
let resourceValues = try contentItemURL.resourceValues(forKeys: keys) | |
guard let isRegularFile = resourceValues.isRegularFile else { | |
preconditionFailure() | |
} | |
guard isRegularFile == true else { | |
continue | |
} | |
var fileSize = resourceValues.fileSize | |
fileSize = fileSize ?? resourceValues.totalFileAllocatedSize | |
guard let size = fileSize else { | |
preconditionFailure("huh? NSURLFileAllocatedSizeKey should always return a value") | |
} | |
// We're good, add up the value. | |
accumulatedSize += UInt64(size) | |
} | |
} | |
} | |
if let error = errorDidOccur { throw error } | |
return accumulatedSize | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment