iOS11系统以下获取系统剩余空间有2种方法:
方法一:
#include <sys/param.h>
#include <sys/mount.h>
+ (NSString *)freeDiskSpaceInBytes{
struct statfs buf;
unsigned long long freeSpace = -1;
if (statfs("/var", &buf) >= 0) {
freeSpace = (unsigned long long)(buf.f_bsize * buf.f_bavail);
}
NSString *str = [NSString stringWithFormat:@"系统剩余空间为:%0.2lld MB",freeSpace/1024/1024];
return str;
}
方法二:
/// 总大小
float totalsize = 0.0;
/// 剩余大小
float freesize = 0.0;
/// 是否登录
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
if (dictionary)
{
NSNumber *_free = [dictionary objectForKey:NSFileSystemFreeSize];
freesize = [_free unsignedLongLongValue]*1.0/(1024);
NSNumber *_total = [dictionary objectForKey:NSFileSystemSize];
totalsize = [_total unsignedLongLongValue]*1.0/(1024);
} else
{
NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
}
NSLog(@"totalsize = %.2f, freesize = %f",totalsize/1024/1024/1024, freesize/1024);
但是在iOS11以上使用这2个方法获取剩余空间不准确了,或者跟系统不一样 iOS11上可以使用以下方法:
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()];
NSDictionary *results = [fileURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey] error:nil];
NSLog(@"剩余空间:%@",results[NSURLVolumeAvailableCapacityForImportantUsageKey]);
// 这里拿到的值的单位是bytes,iOS11是这样算的1000MB = 1,1000进制算的
注意是1000位单位了。不是1024。
网友评论