T
T
timoninas12021-08-20 11:10:24
Swift
timoninas1, 2021-08-20 11:10:24

How to check for disk space in Swift?

For a mobile application, you need to check for free disk space, what is the best way to do this without using third-party libraries?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2021-08-26
@timoninas1

func freeDiskSpaceInGB() -> String? {
            
    let fileURL = URL(fileURLWithPath:"/")
    do {
        let values = try fileURL.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
        if let capacity = values.volumeAvailableCapacityForImportantUsage {
            let formatter = ByteCountFormatter()
            // В каких единицах хотим измерять свободное дисковое пространство
            formatter.allowedUnits = .useGB
            formatter.countStyle = .decimal
            formatter.includesUnit = false
            return formatter.string(fromByteCount: capacity)
        } else {
            print("Невозможно измерять объем")
            return nil
        }
    } catch {
        print("Ошибка: \(error.localizedDescription)")
        return nil
    }
}

Source:
https://developer.apple.com/documentation/foundati...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question