iOS项目框架搭建iOS DeveloperOC 底层

Objective-C 获取iPhone硬盘总容量及空闲容量的3

2017-03-17  本文已影响329人  WonderChang
方法1

总容量:

    struct statfs buf;
    long long totalspace;
    totalspace = 0;
    if(statfs("/private/var", &buf) >= 0){
        totalspace = (long long)buf.f_bsize * buf.f_blocks;
    }
    return totalspace;

空闲容量:

    struct statfs buf;
    long long freespace;
    freespace = 0;
    if(statfs("/private/var", &buf) >= 0){
        freespace = (long long)buf.f_bsize * buf.f_bfree;
    }
    return freespace;

PS. 需要引入头文件#import <sys/mount.h>

方法2

总容量及空闲容量:

    NSDictionary *systemAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:NSHomeDirectory()];
    NSString *diskTotalSize = [systemAttributes objectForKey:@"NSFileSystemSize"];
    NSLog(@"磁盘大小:%@ B", diskTotalSize);
    NSLog(@"磁盘大小:%.2f GB", [diskTotalSize floatValue]/1024/1024/1024);
    NSString *diskFreeSize = [systemAttributes objectForKey:@"NSFileSystemFreeSize"];
    NSLog(@"可用空间:%@ B", diskFreeSize);
    NSLog(@"可用空间:%.2f MB", [diskFreeSize floatValue]/1024/1024);

PS. 这里所用的方法fileSystemAttributesAtPath:在 iOS 2.0 时已被宣告弃用,但在如今最新的SDK中该方法仍然可用。目前只是提示警告信息,在后续版本的 iOS SDK 中也有被移除的可能。

方法3

依据方法2提供的思路,加以完善。
总容量及空闲容量:

    float totalSpace;
    float freeSpace;

    NSError *error = nil;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    
    if (dictionary) {
        
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        
        totalSpace = [fileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;
        
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        
        freeSpace = [freeFileSystemSizeInBytes floatValue]/1024.0f/1024.0f;
        
    } else {
        
        totalSpace = 0;
        
        freeSpace = 0;

    }
上一篇下一篇

猜你喜欢

热点阅读