ios-清理应用缓存

思路:清除沙盒缓存文件夹下的内容
实现功能:清理缓存,计算并提示用户清理了多少缓存
代码实现:(自己申明记录缓存大小的变量)

1.获取沙盒缓存路径,开启线程进行清理操作

//清除缓存
- (void)clear
{
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       // 获取沙盒路径
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];

                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];

//                       NSLog(@"files :%lu",[files count]);

                       _cacheSize=[self folderSizeAtPath:cachPath];

                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                       [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});

}

2.在上面的方法中需要计算清理了多少缓存,下面两个方法结合实现这个功能

// 计算缓存文件夹大小
- (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){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

// 计算缓存文件大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

3.提示用户清理成功

// 提示用户清理成功
-(void)clearCacheSuccess
{
    NSString *info = [NSString stringWithFormat:@"成功清理%.2fMb缓存",_cacheSize];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清除成功" message:info preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];

    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];

}

posted on 2015-11-12 11:23  MrYude  阅读(404)  评论(0编辑  收藏  举报

导航