获取沙盒文件Cache文件内的文件夹的大小

来源:互联网 发布:cydia软件源下载 编辑:程序博客网 时间:2024/06/13 10:36

- (void)videoPlay{

     //创建沙盒内的文件夹

    NSFileManager *fileManager=[NSFileManager defaultManager];
    animationPath = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/Animation"];
    tempPath = [animationPath stringByAppendingPathComponent:@"/Temp"];
    cachePath = [animationPath stringByAppendingPathComponent:@"/Cache"];
    if (![fileManager fileExistsAtPath:cachePath]) {
        [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (![fileManager fileExistsAtPath:tempPath]) {
        [fileManager createDirectoryAtPath:tempPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if ([fileManager fileExistsAtPath:animationPath]) {
        float maxSize = [self folderSizeAtPath:animationPath];

       //判断文件夹内存是否超出我们的最大值
        if (maxSize > 40.f) {
            cacheFileArray  =[fileManager contentsOfDirectoryAtPath:cachePath error:NULL];
            for (NSString *file in cacheFileArray) {
                NSString *path =[cachePath stringByAppendingPathComponent:file];
                [fileManager removeItemAtPath:path error:nil];
            }
            tempFileArray  =[fileManager contentsOfDirectoryAtPath:cachePath error:NULL];
            for (NSString *file in tempFileArray) {
                NSString *path =[tempPath stringByAppendingPathComponent:file];
                [fileManager removeItemAtPath:path error:nil];
            }
        }
    }
}

//遍历文件夹获得文件夹大小,返回多少MB

- (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;
}
0 0