Ios obtains the cache file size and clears the cache. ios obtains the cache size.
Mobile applications generally perform offline cache processing when processing network resources. The image cache is the most typical one. The popular offline cache framework is SDWebImage.
However, the offline cache occupies the storage space of the mobile phone. Therefore, the cache cleanup function is a standard function for information, shopping, and reading apps.
The implementation of the offline cache function introduced today is mainly divided into obtaining the cache file size and clearing the cache file.
1. Get the cache file size
-(Float) readCacheSize
{
NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) firstObject];
Return [self folderSizeAtPath: cachePath];
}
Because cached files exist in the sandbox, we can use the NSFileManager API to calculate the cached file size.
// Retrieve the size of the folder by traversing the folder and return M
-(Float) folderSizeAtPath :( NSString *) folderPath {
NSFileManager * manager = [NSFileManager defamanager manager];
If (! [Manager fileExistsAtPath: folderPath]) return 0;
NSEnumerator * childFilesEnumerator = [[manager subpathsAtPath: folderPath] objectEnumerator];
NSString * fileName;
Long folderSize = 0;
While (fileName = [childFilesEnumerator nextObject])! = Nil ){
// Obtain the full file path
NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent: fileName];
FolderSize + = [self fileSizeAtPath: fileAbsolutePath];
}
Return folderSize/(1024.0*1024.0 );
}
// Calculate the size of a single file
-(Long) fileSizeAtPath :( NSString *) filePath {
NSFileManager * manager = [NSFileManager defamanager manager];
If ([manager fileExistsAtPath: filePath]) {
Return [[manager attributesOfItemAtPath: filePath error: nil] fileSize];
}
Return 0;
}
2. Clear 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;
// Obtain the full file path
NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent: p];
If ([[NSFileManager defaultManager] fileExistsAtPath: fileAbsolutePath]) {
[[NSFileManager defaultManager] removeItemAtPath: fileAbsolutePath error: & error];
}
}
// Read the cache size
Float cacheSize = [self readCacheSize] * 1024;
Self. cacheSize. text = [NSString stringWithFormat: @ "%. 2fKB", cacheSize];
}