IOS recursive folder size

I store files in a directory of local documents, separated by folders. Is there an easy way to get the file size of the contents of the document directory and all subdirectories on the iPhone?

I can manually iterate over folders and add file size, but I hope there is something cleaner and more efficient there.

Thank!

+5
source share
2 answers

You can recursively iterate 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;
}
+4
source

Approach and performance vary by iOS version. For iOS 4.0 and later, you can create a category on NSFileManagerwith 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;
}
+3
source

All Articles