iOS 獲取手機剩餘儲存空間
阿新 • • 發佈:2019-01-31
兩種方法均與嗶哩嗶哩剩餘記憶體統計比較過,資料一樣,且都小於iOS系統 <設定>裡統計的資料;
方法一:
#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);