iOS - Get sum of filesize in directory

僤鯓⒐⒋嵵緔 提交于 2019-12-04 13:16:25

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/9314954/ios-get-sum-of-filesize-in-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!