Mobile applications in the processing of network resources, generally do offline cache processing, which is the most typical picture cache, where the popular offline cache framework is sdwebimage.
However, offline caching takes up storage space on your phone, so the cache cleanup function is basically a standard feature for information, shopping, and reading apps.
The implementation of the offline caching feature introduced today is mainly divided into the cache file size acquisition, clear cache file implementation.
1. Get the size of the cache file
-(float) readcachesize
{
NSString *cachepath = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) firstObject];
return [self foldersizeatpath:cachepath];
}
Because the cache file exists in the sandbox, we can use the Nsfilemanager API to calculate the size of the cache file.
Traverse folder to get folder size, return how many 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) {
Get file Full path
NSString * Fileabsolutepath = [FolderPath stringbyappendingpathcomponent:filename];
Foldersize + = [self filesizeatpath:fileabsolutepath];
}
Return foldersize/(1024.0 * 1024.0);
}
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;
Get file Full path
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];
}
iOS gets the size of the cache file and clears the cache