如何在iOS 11上检测iPhone / iPad设备上的总可用/可用磁盘空间

时间:2018-01-30 08:19:04

标签: ios objective-c iphone ipad ios11

在iOS 11中,我无法从字典键NSFileSystemFreeSize获取设备的正确可用大小(磁盘空间)。而是提供34.4 GB,它提供4 GB的可用空间。

以下是我正在使用的代码

pragma mark - Formatter

- (NSString *)memoryFormatter:(long long)diskSpace
{
    NSString *formatted;
    double bytes = 1.0 * diskSpace;
    double megabytes = bytes / MB;
    double gigabytes = bytes / GB;
    if (gigabytes >= 1.0)
        formatted = [NSString stringWithFormat:@"%.2f GB", gigabytes];
    else if (megabytes >= 1.0)
        formatted = [NSString stringWithFormat:@"%.2f MB", megabytes];
    else
        formatted = [NSString stringWithFormat:@"%.2f bytes", bytes];

    return formatted;
}

#pragma mark - Methods

- (NSString *)totalDiskSpace {
    long long space = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemSize] longLongValue];
    return [self memoryFormatter:space];
}

- (NSString *)freeDiskSpace {
    long long freeSpace = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] longLongValue];
    return [self memoryFormatter:freeSpace];
}

- (NSString *)usedDiskSpace {
    return [self memoryFormatter:[self usedDiskSpaceInBytes]];
}

- (CGFloat)totalDiskSpaceInBytes {
    long long space = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemSize] longLongValue];
    return space;
}

- (CGFloat)freeDiskSpaceInBytes {
    long long freeSpace = [[[[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil] objectForKey:NSFileSystemFreeSize] longLongValue];
    return freeSpace;
}

- (CGFloat)usedDiskSpaceInBytes {
    long long usedSpace = [self totalDiskSpaceInBytes] - [self freeDiskSpaceInBytes];
    return usedSpace;
}

4 个答案:

答案 0 :(得分:1)

目标C (已转换)

- (uint64_t)freeDiskspace
{
    uint64_t totalSpace = 0;
    uint64_t totalFreeSpace = 0;

    __autoreleasing 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 unsignedLongLongValue];
      totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
      NSLog(@"Memory Capacity of %llu MiB with %llu MiB Free memory available.", ((totalSpace/1024ll)/1024ll), ((totalFreeSpace/1024ll)/1024ll));
   }

   else 
   {  
      NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %d", [error domain], [error code]);  
   }  

   return totalFreeSpace;
}

答案 1 :(得分:0)

这是我通常的做法

func deviceRemainingFreeSpaceInBytes() -> Int64?
{
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
    guard
        let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: documentDirectory),
        let freeSize = systemAttributes[.systemFreeSize] as? NSNumber
        else {
            // handle failure
            return nil
    }
    return freeSize.int64Value // this returns bytes - scales as required for MB / GB
}

答案 2 :(得分:0)

SWIFT 4:

func getFreeDiskspace() -> UInt64 
{

 let totalSpace: UInt64 = 0

 let totalFreeSpace: UInt64 = 0

 var error: Error? = nil

 let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)

 let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last ?? "")


if dictionary 
{

 var fileSystemSizeInBytes = dictionary[.systemSize]

 var freeFileSystemSizeInBytes = dictionary[.systemFreeSize]

 totalSpace = fileSystemSizeInBytes as UInt64? ?? 0

 totalFreeSpace = freeFileSystemSizeInBytes as UInt64? ?? 0

 print("Memory Capacity of \((totalSpace / 1024) / 1024) MiB with \((totalFreeSpace / 1024) / 1024) MiB Free memory available.")

}

else
{

 print("Error Obtaining System Memory Info: Domain = \((error as NSError?)?.domain), Code = \(Int(error.code))")



 return totalFreeSpace

}


}

答案 3 :(得分:0)

因此,如果人们遇到无法获得正确的可用大小的问题,请使用NSURL resourceValuesForKeys来获取可用空间。

[ fileURL resourceValuesForKeys:@[NSURLVolumeAvailableCapacityForImportantUsageKey ] error:&error];
        
double = availableSizeInBytes = [ results[NSURLVolumeAvailableCapacityForImportantUsageKey] doubleValue ];

参考https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/#couchbase.repository.indexing