iOS清除缓存,实时显示缓存大小

来源:互联网 发布:根据域名查询ip地址 编辑:程序博客网 时间:2024/05/21 17:04


这是我做的清除缓存功能,还是很好用的


//

//  SettingViewController.m

//  GuiguziFoot

//

//  Created by LANJIE on 16/5/20.

//  Copyright © 2016 俞涛涛. All rights reserved.

//


#import "SettingViewController.h"

#import "MBProgressHUD.h"

 


@interface SettingViewController ()

@property (weak, nonatomic) IBOutletUILabel *cacheLabel;


@end


@implementation SettingViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    _cacheLabel.text=[NSStringstringWithFormat:@"%.1fM",[selffilePath]];//显示缓存大小

    // Do any additional setup after loading the view from its nib.

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


/*

#pragma mark - Navigation


// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    // Get the new view controller using [segue destinationViewController].

    // Pass the selected object to the new view controller.

}

*/

//蒙版

- (void)textExample {

    MBProgressHUD *hud = [MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];

    

    // Set the annular determinate mode to show task progress.

    hud.mode = MBProgressHUDModeText;

    hud.label.text =NSLocalizedString(@"清除缓存成功",@"HUD message title");

    // Move to bottm center.

    hud.offset =CGPointMake(0.f, 0.f);

    

    [hud hideAnimated:YESafterDelay:2.f];

}

/**

 *  清除缓存

 *

 *  @param sender

 */

- (IBAction)cleanCache:(UIControl *)sender {

    UIAlertController *alertSheet=[UIAlertControlleralertControllerWithTitle:@"清除缓存"message:@"确认清除缓存"preferredStyle:UIAlertControllerStyleAlert];

    

    // 创建按钮

    UIAlertAction *okAction = [UIAlertActionactionWithTitle:@"确定"style:(UIAlertActionStyleDefault)handler:^(UIAlertAction *action) {

       //清除缓存方法

        [selfclearFile];

 


    }];

 

    //注意取消按钮只能添加一个

    UIAlertAction *cancelAction = [UIAlertActionactionWithTitle:@"取消"style:(UIAlertActionStyleCancel)handler:^(UIAlertAction *action) {

        //点击按钮后的方法直接在这里面写

       NSLog(@"取消·");

    }];

    [alertSheetaddAction:okAction];

//    [alertSheet addAction:okAction2];

    [alertSheetaddAction:cancelAction];

    [selfpresentViewController:alertSheet animated:YEScompletion:nil];

    

    

}


- (IBAction)backClick:(id)sender {

    [self.navigationControllerpopViewControllerAnimated:YES];

}




// 显示缓存大小

-(float )filePath

{

    

    NSString * cachPath = [NSSearchPathForDirectoriesInDomains ( NSCachesDirectory ,NSUserDomainMask , YES )firstObject ];

    

   return [ selffolderSizeAtPath :cachPath];

    

}

//1:首先我们计算一下单个文件的大小


- (long long ) fileSizeAtPath:(NSString *) filePath{

    

    NSFileManager * manager = [NSFileManager defaultManager ];

    

   if ([manager fileExistsAtPath :filePath]){

        

       return [[manager attributesOfItemAtPath :filePatherror : nil ]fileSize ];

    }

    

   return 0 ;

    

}

//2:遍历文件夹获得文件夹大小,返回多少 M(提示:你可以在工程界设置()m


- (float ) folderSizeAtPath:( NSString *) folderPath{

    

    NSFileManager * manager = [NSFileManager defaultManager ];

    

   if (![manager fileExistsAtPath :folderPath])return 0 ;

    

   NSEnumerator *childFilesEnumerator = [[managersubpathsAtPath :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 );

    

}



// 清理缓存


- (void)clearFile

{

    dispatch_async(

                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

                   , ^{

    NSString * cachPath = [NSSearchPathForDirectoriesInDomains ( NSCachesDirectory ,NSUserDomainMask , YES )firstObject ];

    

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

    

   NSLog ( @"cachpath = %@" , cachPath);

    

   for ( NSString * pin files) {

        

       NSError * error = nil ;

        

        NSString * path = [cachPathstringByAppendingPathComponent :p];

        

        if ([[NSFileManager defaultManager ]fileExistsAtPath :path]) {

            

            [[ NSFileManagerdefaultManager ] removeItemAtPath :patherror :&error];

            

        }

        

    }

    [ selfperformSelectorOnMainThread : @selector (clearCachSuccess)withObject : nilwaitUntilDone : YES ];});

    

}

-(void)clearCachSuccess

{

   NSLog ( @" 清理成功 " );

//    [self.view setNeedsDisplay];

    _cacheLabel.text=[NSStringstringWithFormat:@"%.1fM",[selffilePath]];

    [selftextExample];


}


@end


1 0
原创粉丝点击