Search code examples
objective-ciosios5directorynsfilemanager

iOS - Get sum of filesize in directory


I have the following code I use to cache photos I load off Flickr in the device's memory:

NSURL *urlForPhoto = [FlickrFetcher urlForPhoto:self.photo format:FlickrPhotoFormatLarge];
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [rootPath stringByAppendingString:[self.photo objectForKey:FLICKR_PHOTO_ID]];
NSData *dataForPhoto;
NSError *error = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
    dataForPhoto = [NSData dataWithContentsOfFile:imagePath];
} else {
    dataForPhoto = [NSData dataWithContentsOfURL:urlForPhoto];
    [dataForPhoto writeToFile:imagePath atomically:YES];
}

I want to limit this to 10MB and then if the limit is reached to remove the oldest photo in the cache, how can I get the total size of all the files I've saved and check which one is the oldest?


Solution

  • You can get the size of a file like so

    NSError *attributesError = nil;
    
        NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
    
        int fileSize = [fileAttributes fileSize];
    

    So you can maybe iterate through all the files in the folder and add up the file sizes...not sure if theres a direct way to get the directory size, also theres this SO post talking about this aswell, you can find a solution here

    To find the creation date of the file you can do

    NSString *path = @"";
        NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
        NSDate *result = [fileAttribs valueForKey:NSFileCreationDate]; //or NSFileModificationDate
    

    Hope it helps