iOS开发之清除缓存功能的实现

2020-01-17 22:07:51于丽

前言

移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage。但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯、购物、阅读类app的标配功能。

清除缓存基本上都是在设置界面的某一个Cell,于是我们可以把清除缓存封装在某一个自定义Cell中

如下图所示:

ios,清除缓存功能,清除缓存,清除缓存完整代码

实现的具体步骤

使用注意:过程中需要用到第三方库,请提前安装好:SDWebImageSVProgressHUD

1. 创建自定义Cell,命名为GYLClearCacheCell

重写initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier方法,设置基本内容,如文字等等;

主要代码如下:


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
 {
 if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
  // 设置加载视图
  UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  [loadingView startAnimating];
  self.accessoryView = loadingView;

  //设置文字
  self.textLabel.text = @"清楚缓存";
  self.detailTextLabel.text = @"正在计算"; 
 }
 return self;
}

2. 计算缓存文件大小

缓存文件包括两部分,一部分是使用SDWebImage缓存的内容,其次可能存在自定义的文件夹中的内容(视频,音频等内容),于是计算要分两部分

主要代码如下:


unsigned long long size =
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"CustomFile"].fileSize;
//fileSize是封装在Category中的。

size += [SDImageCache sharedImageCache].getSize; //CustomFile + SDWebImage 缓存

//设置文件大小格式
NSString sizeText = nil;
if (size >= pow(10, 9)) {
 sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
}else if (size >= pow(10, 6)) {
 sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
}else if (size >= pow(10, 3)) {
 sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
}else {
 sizeText = [NSString stringWithFormat:@"%zdB", size];
}

上述两个方法都是在主线程中完成的,如果缓存文件大小非常大的话,计算时间会比较长,会导致应用卡死,考虑到该问题,因此需要将上述代码放到子线程中完成。

3. 添加手势监听