IOS获取缓存文件的大小并清除缓存文件的方法
移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage。
但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯、购物、阅读类app的标配功能。
今天介绍的离线缓存功能的实现,主要分为缓存文件大小的获取、清除缓存文件的实现。
1.获取缓存文件的大小
-(float)readCacheSize
{
NSString*cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
return[selffolderSizeAtPath:cachePath];
}
由于缓存文件存在沙箱中,我们可以通过NSFileManagerAPI来实现对缓存文件大小的计算。
//遍历文件夹获得文件夹大小,返回多少M
-(float)folderSizeAtPath:(NSString*)folderPath{
NSFileManager*manager=[NSFileManagerdefaultManager];
if(![managerfileExistsAtPath:folderPath])return0;
NSEnumerator*childFilesEnumerator=[[managersubpathsAtPath:folderPath]objectEnumerator];
NSString*fileName;
longlongfolderSize=0;
while((fileName=[childFilesEnumeratornextObject])!=nil){
//获取文件全路径
NSString*fileAbsolutePath=[folderPathstringByAppendingPathComponent:fileName];
folderSize+=[selffileSizeAtPath:fileAbsolutePath];
}
returnfolderSize/(1024.0*1024.0);
}
//计算单个文件的大小
-(longlong)fileSizeAtPath:(NSString*)filePath{
NSFileManager*manager=[NSFileManagerdefaultManager];
if([managerfileExistsAtPath:filePath]){
return[[managerattributesOfItemAtPath:filePatherror:nil]fileSize];
}
return0;
}
2.清除缓存
-(void)clearFile
{
NSString*cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
NSArray*files=[[NSFileManagerdefaultManager]subpathsAtPath:cachePath];
//NSLog(@"cachpath=%@",cachePath);
for(NSString*pinfiles){
NSError*error=nil;
//获取文件全路径
NSString*fileAbsolutePath=[cachePathstringByAppendingPathComponent:p];
if([[NSFileManagerdefaultManager]fileExistsAtPath:fileAbsolutePath]){
[[NSFileManagerdefaultManager]removeItemAtPath:fileAbsolutePatherror:&error];
}
}
//读取缓存大小
floatcacheSize=[selfreadCacheSize]*1024;
self.cacheSize.text=[NSStringstringWithFormat:@"%.2fKB",cacheSize];
}
以上所述是小编给大家介绍的IOS获取缓存文件的大小并清除缓存文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!