Is there a way to determine the amount of disk space an app has used in iOS?

≡放荡痞女 提交于 2020-01-06 02:31:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!