iOS 获取手机总空间、剩余空间,文件夹占用空间大小

2020-06-08  本文已影响0人  gaookey

#import <Foundation/Foundation.h>

#include <sys/param.h>
#include <sys/mount.h>

@interface DiskSpaceTool : NSObject

/**
 手机剩余空间
 */
+ (NSString *)freeDiskSpaceInBytes;

/**
 手机总空间
 */
+ (NSString *)totalDiskSpaceInBytes;

/**
 某个文件夹占用空间的大小
 */
+ (NSString *)folderSizeAtPath:(NSString*) folderPath;

@end


#import "DiskSpaceTool.h"

@implementation DiskSpaceTool

+ (NSString *)freeDiskSpaceInBytes;
{
    struct statfs buf;
    long long freespace = -1;
    if(statfs("/var", &buf) >= 0){
        freespace = (long long)(buf.f_bsize * buf.f_bfree);
    }
    return [self humanReadableStringFromBytes:freespace];
}

+ (NSString *)totalDiskSpaceInBytes;
{
    struct statfs buf;
    long long freespace = 0;
    if (statfs("/", &buf) >= 0) {
        freespace = (long long)buf.f_bsize * buf.f_blocks;
    }
    if (statfs("/private/var", &buf) >= 0) {
        freespace += (long long)buf.f_bsize * buf.f_blocks;
    }
    return [self humanReadableStringFromBytes:freespace];
}

// 遍历文件夹获得文件夹大小
+ (NSString *) 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 [self humanReadableStringFromBytes:folderSize];
}

// 单个文件的大小
+ (long long) fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

// 计算文件大小
+ (NSString *)humanReadableStringFromBytes:(unsigned long long)byteCount
{
    float numberOfBytes = byteCount;
    int multiplyFactor = 0;
    
    NSArray *tokens = [NSArray arrayWithObjects:@"bytes",@"KB",@"MB",@"GB",@"TB",@"PB",@"EB",@"ZB",@"YB",nil];
    
    while (numberOfBytes > 1024) {
        numberOfBytes /= 1024;
        multiplyFactor++;
    }
    
    return [NSString stringWithFormat:@"%4.2f %@",numberOfBytes, [tokens objectAtIndex:multiplyFactor]];
}

@end

上一篇 下一篇

猜你喜欢

热点阅读