How to detect total available/free disk space on the iPhone/iPad device?

后端 未结 18 1750
别跟我提以往
别跟我提以往 2020-11-22 11:14

I\'m looking for a better way to detect available/free disk space on the iPhone/iPad device programmatically.
Currently I\'m using the NSFileManager to detect the disk s

18条回答
  •  孤街浪徒
    2020-11-22 11:40

    Here's my answer and why it's better.

    Answer (Swift):

    func remainingDiskSpaceOnThisDevice() -> String {
        var remainingSpace = NSLocalizedString("Unknown", comment: "The remaining free disk space on this device is unknown.")
        if let attributes = try? FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()),
            let freeSpaceSize = attributes[FileAttributeKey.systemFreeSize] as? Int64 {
            remainingSpace = ByteCountFormatter.string(fromByteCount: freeSpaceSize, countStyle: .file)
        }
        return remainingSpace
    }
    

    Answer (Objective-C):

    - (NSString *)calculateRemainingDiskSpaceOnThisDevice
    {
        NSString *remainingSpace = NSLocalizedString(@"Unknown", @"The remaining free disk space on this device is unknown.");
        NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
        if (dictionary) {
            long long freeSpaceSize = [[dictionary objectForKey:NSFileSystemFreeSize] longLongValue];
            remainingSpace = [NSByteCountFormatter stringFromByteCount:freeSpaceSize countStyle:NSByteCountFormatterCountStyleFile];
        }
        return remainingSpace;
    }
    

    Why it's better:

    • Utilizes Cocoa's built in library NSByteCountFormatter, meaning no crazy manual calculations from bytes to gigabytes. Apple does this for you!
    • Easily translatable: NSByteCountFormatter does this for you. E.g. When the device's language is set to English the string will read 248.8 MB but will read 248,8 Mo when set to French, et cetera for other languages.
    • A default value is given in case of an error.

提交回复
热议问题