IOS gets the size of the cache file and clears the method of the cache file

  • 2021-01-25 07:57:02
  • OfStack

When mobile applications process network resources, they usually do offline caching, among which picture caching is the most typical. The popular offline caching framework is SDWebImage.

However, offline caching takes up storage space on the phone, so cache cleanup has become a standard feature in app for information, shopping, and reading.

The realization of offline caching function introduced today is mainly divided into the realization of obtaining and clearing cache files of the size of cache files.

1. Get the size of the cache file


-( float )readCacheSize
{
NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
return [ self folderSizeAtPath :cachePath];
}

Since the cache files are in the sandbox, we can use NSFileManager API to calculate the size of the cache files.


//  Iterate through the folder to get the size of the folder and how much is returned  M
- ( float ) folderSizeAtPath:( NSString *) folderPath{
NSFileManager * manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath :folderPath]) return 0 ;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
NSString * fileName;
long long folderSize = 0 ;
while ((fileName = [childFilesEnumerator nextObject]) != nil ){
// Gets the full path to the file 
NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
folderSize += [ self fileSizeAtPath :fileAbsolutePath];
}
return folderSize/( 1024.0 * 1024.0);
}
//  To calculate   The size of a single file 
- ( long long ) fileSizeAtPath:( NSString *) filePath{
NSFileManager * manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath :filePath]){
return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
}
return 0;
}

2. Clear the cache


- (void)clearFile
{
NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
//NSLog ( @"cachpath = %@" , cachePath);
for ( NSString * p in files) {
NSError * error = nil ;
// Gets the full path to the file 
NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
[[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
}
}
// Read cache size 
float cacheSize = [self readCacheSize] *1024;
self.cacheSize.text = [NSString stringWithFormat:@"%.2fKB",cacheSize];
}

Related articles: