问题
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.
回答1:
I ended up figuring out how to do this:
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;
}
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.
来源:https://stackoverflow.com/questions/49991278/is-there-a-way-to-determine-the-amount-of-disk-space-an-app-has-used-in-ios