获取存储空间及占用空间
October 31, 2016
iOS:获取存储空间及占用空间
获得单个文件的大小
/**
获得单个文件的大小
@param filePath 文件路径
@return 单位(字节)
*/
- (long long) fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
获得文件夹(遍历)的大小
/**
获得文件夹(遍历)的大小
@param folderPath 文件夹路径
@return 单位(M)
*/
- (float ) 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 folderSize/(1024.0*1024.0);
}
根据上面的获得文件夹(遍历)的大小
的方法, 可获取当前应用占用空间
//获取当前应用的目录
NSString *destPath = NSHomeDirectory();
//计算目录占用的控件
CGFloat AppFolderSize = [self folderSizeAtPath:destPath];
获取本地全部空间(去除系统占用大小)&剩余空间
/**
获取硬盘空间及剩余可用空间
*/
-(void)getFreeDiskspace {
float totalSpace;
float totalFreeSpace;
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];
NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
totalSpace = [fileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;
totalFreeSpace = [freeFileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;
NSLog(@"Memory Capacity of %f GB with %f GB Free memory available.", totalSpace, totalFreeSpace);
} else {
NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], [error code]);
}
}