Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS recursive folder size

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 !

like image 254
Alex Stone Avatar asked May 23 '12 00:05

Alex Stone


2 Answers

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;
}
like image 146
Dmytro Mykhailov Avatar answered Sep 19 '22 17:09

Dmytro Mykhailov


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;
}
like image 21
voromax Avatar answered Sep 20 '22 17:09

voromax