IOS 缓存文件的清除实现代码
移动互联网 APP的应用开发,必须要时刻注意用户体验,以免造成APP或者手机及其他移动设备的卡死情况,以下是对缓存文件的处理。
移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为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]; }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!