IOS - get the amount of files in a directory

I have the following code that I use to cache photos. I load Flickr into the device 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 10 MB, and then if the limit is reached for deleting the oldest photo in the cache, how can I get the total size of all the files that I saved and check which one is the oldest?

+6
source share
1 answer

You can get this file size

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

So, you can possibly iterate over all the files in the folder and add the file sizes ... not sure if theres a direct way to get the size of the directory, also theres this SO message about it as well, you can find a solution here

To find the file creation date you can do

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

Hope this helps

+9
source

Source: https://habr.com/ru/post/908639/


All Articles