有没有一种方法可以确定应用程序在iOS中已使用的磁盘空间量? [英] Is there a way to determine the amount of disk space an app has used in iOS?
问题描述
我看过很多关于如何获取iOS设备的可用空间量或iOS设备具有多少可用空间的文章,但是有没有办法确定应用程序本身已使用了多少空间? (包括应用程序本身及其所有资源/文档/缓存/等).该值将与设置"->常规"->"iPhone存储"中看到的值相同.
I've seen many posts about how to get the amount of free space the iOS device has, or how much free space the iOS device has, but is there a way to determine how much space the app itself has used? (Including the app itself and all of its resources/documents/cache/etc). This would be the same value that can be seen in Settings->General->iPhone Storage.
推荐答案
我最终弄清楚了如何做到这一点:
I ended up figuring out how to do this:
我在NSFileManager
上创建了一个类别并添加:
I created a category on NSFileManager
and added:
-(NSUInteger)applicationSize
NSString *appgroup = @"Your App Group"; // Might not be necessary in your case.
NSURL *appGroupURL = [self containerURLForSecurityApplicationGroupIdentifier:appgroup];
NSURL *documentsURL = [[self URLsForDirectory: NSDocumentDirectory inDomains: NSUserDomainMask] firstObject];
NSURL *cachesURL = [[self URLsForDirectory: NSCachesDirectory inDomains: NSUserDomainMask] firstObject];
NSUInteger appGroupSize = [appGroupURL fileSize];
NSUInteger documentsSize = [documentsURL fileSize];
NSUInteger cachesSize = [cachesURL fileSize];
NSUInteger bundleSize = [[[NSBundle mainBundle] bundleURL] fileSize];
return appGroupSize + documentsSize + cachesSize + bundleSize;
}
我还在NSURL
上添加了以下类别:
I also added a category on NSURL
with the following:
-(NSUInteger)fileSize
{
BOOL isDir = NO;
[[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDir];
if (isDir)
return [self directorySize];
else
return [[[[NSFileManager defaultManager] attributesOfItemAtPath:self.path error:nil] objectForKey:NSFileSize] unsignedIntegerValue];
}
-(NSUInteger)directorySize
{
NSUInteger result = 0;
NSArray *properties = @[NSURLLocalizedNameKey, NSURLCreationDateKey, NSURLLocalizedTypeDescriptionKey];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:self includingPropertiesForKeys:properties options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];
for (NSURL *url in files)
{
result += [url fileSize];
}
return result;
}
如果您有很多应用程序数据,则需要一点时间才能运行,但是它可以正常工作.
It takes a bit to run if you have a lot of app data, but it works.
这篇关于有没有一种方法可以确定应用程序在iOS中已使用的磁盘空间量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!