How to detect total available/free disk space on the iPhone/iPad device?

后端 未结 18 2039
别跟我提以往
别跟我提以往 2020-11-22 11:14

I\'m looking for a better way to detect available/free disk space on the iPhone/iPad device programmatically.
Currently I\'m using the NSFileManager to detect the disk s

18条回答
  •  再見小時候
    2020-11-22 11:52

    If you need formatted string with size you can take a look at nice library on GitHub:

    #define MB (1024*1024)
    #define GB (MB*1024)
    
    @implementation ALDisk
    
    #pragma mark - Formatter
    
    + (NSString *)memoryFormatter:(long long)diskSpace {
        NSString *formatted;
        double bytes = 1.0 * diskSpace;
        double megabytes = bytes / MB;
        double gigabytes = bytes / GB;
        if (gigabytes >= 1.0)
            formatted = [NSString stringWithFormat:@"%.2f GB", gigabytes];
        else if (megabytes >= 1.0)
            formatted = [NSString stringWithFormat:@"%.2f MB", megabytes];
        else
            formatted = [NSString stringWithFormat:@"%.2f bytes", bytes];
    
        return formatted;
    }
    
    #pragma mark - Methods
    
    + (NSString *)totalDiskSpace {
        long long space = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemSize] longLongValue];
        return [self memoryFormatter:space];
    }
    
    + (NSString *)freeDiskSpace {
        long long freeSpace = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] longLongValue];
        return [self memoryFormatter:freeSpace];
    }
    
    + (NSString *)usedDiskSpace {
        return [self memoryFormatter:[self usedDiskSpaceInBytes]];
    }
    
    + (CGFloat)totalDiskSpaceInBytes {
        long long space = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemSize] longLongValue];
        return space;
    }
    
    + (CGFloat)freeDiskSpaceInBytes {
        long long freeSpace = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] longLongValue];
        return freeSpace;
    }
    
    + (CGFloat)usedDiskSpaceInBytes {
        long long usedSpace = [self totalDiskSpaceInBytes] - [self freeDiskSpaceInBytes];
        return usedSpace;
    }
    

提交回复
热议问题