有没有办法确定应用程序在 iOS 中使用的磁盘数量 space?

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

我看过很多关于如何获取 iOS 设备的免费 space 数量,或者 iOS 设备的免费 space 数量的帖子,但有没有办法确定应用程序本身使用了多少 space? (包括应用程序本身及其所有 resources/documents/cache/etc)。这与在设置->常规->iPhone 存储中可以看到的值相同。

我最终弄清楚了如何做到这一点:

我在 NSFileManager 上创建了一个类别并添加了:

-(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 上添加了一个类别,内容如下:

-(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;
}

如果您有大量应用程序数据,运行 需要一些时间,但它确实有效。