I'm storing files in a local documents directory, separated by folders. Is there an easy way for me to get the file size of the contents of the documents directory and all subdirectories on an iPhone?
I can manually iterate over folders and keep adding file size, but I'm hoping there's something cleaner and more efficient.
Thank you !
You can recursively go over all folders and get the size. Like this:
+(NSUInteger)getDirectoryFileSize:(NSURL *)directoryUrl
{
NSUInteger result = 0;
NSArray *properties = [NSArray arrayWithObjects: NSURLLocalizedNameKey,
NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey, nil];
NSArray *array = [[NSFileManager defaultManager]
contentsOfDirectoryAtURL:directoryUrl
includingPropertiesForKeys:properties
options:(NSDirectoryEnumerationSkipsHiddenFiles)
error:nil];
for (NSURL *fileSystemItem in array) {
BOOL directory = NO;
[[NSFileManager defaultManager] fileExistsAtPath:[fileSystemItem path] isDirectory:&directory];
if (!directory) {
result += [[[[NSFileManager defaultManager] attributesOfItemAtPath:[fileSystemItem path] error:nil] objectForKey:NSFileSize] unsignedIntegerValue];
}
else {
result += [CacheManager getDirectoryFileSize:fileSystemItem];
}
}
return result;
}
The approach and efficiency vary depends on the iOS version. For iOS 4.0 and later you can make a category on NSFileManager
with something like this:
- (unsigned long long)contentSizeOfDirectoryAtURL:(NSURL *)directoryURL
{
unsigned long long contentSize = 0;
NSDirectoryEnumerator *enumerator = [self enumeratorAtURL:directoryURL includingPropertiesForKeys:[NSArray arrayWithObject:NSURLFileSizeKey] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:NULL];
NSNumber *value = nil;
for (NSURL *itemURL in enumerator) {
if ([itemURL getResourceValue:&value forKey:NSURLFileSizeKey error:NULL]) {
contentSize += value.unsignedLongLongValue;
}
}
return contentSize;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With