Skip to content

Instantly share code, notes, and snippets.

@ankitthakur
Created June 10, 2019 06:41
Show Gist options
  • Save ankitthakur/7aded36252ffb609a587fec64cb429d2 to your computer and use it in GitHub Desktop.
Save ankitthakur/7aded36252ffb609a587fec64cb429d2 to your computer and use it in GitHub Desktop.
iOS & Mac Device Disk Space Information
import Foundation
class ByteInfo {
class func GBFormatter(_ bytes: Int64) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = ByteCountFormatter.Units.useGB
formatter.countStyle = ByteCountFormatter.CountStyle.decimal
formatter.includesUnit = false
return formatter.string(fromByteCount: bytes) as String
}
class func MBFormatter(_ bytes: Int64) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = ByteCountFormatter.Units.useMB
formatter.countStyle = ByteCountFormatter.CountStyle.decimal
formatter.includesUnit = false
return formatter.string(fromByteCount: bytes) as String
}
class func KBFormatter(_ bytes: Int64) -> String {
let formatter = ByteCountFormatter()
formatter.allowedUnits = ByteCountFormatter.Units.useKB
formatter.countStyle = ByteCountFormatter.CountStyle.decimal
formatter.includesUnit = false
return formatter.string(fromByteCount: bytes) as String
}
}
class DeviceDiskInformation {
class var totalDiskSpaceInBytes:Int64 {
get {
do {
let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String)
let space = (systemAttributes[FileAttributeKey.systemSize] as? NSNumber)?.int64Value
return space!
} catch {
return 0
}
}
}
class var freeDiskSpaceInBytes:Int64 {
get {
do {
let systemAttributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory() as String)
let freeSpace = (systemAttributes[FileAttributeKey.systemFreeSize] as? NSNumber)?.int64Value
return freeSpace!
} catch {
return 0
}
}
}
class var usedDiskSpaceInBytes:Int64 {
get {
let usedSpace = totalDiskSpaceInBytes - freeDiskSpaceInBytes
return usedSpace
}
}
}
print("---GB---")
print(ByteInfo.GBFormatter(DeviceDiskInformation.totalDiskSpaceInBytes))
print(ByteInfo.GBFormatter(DeviceDiskInformation.freeDiskSpaceInBytes))
print(ByteInfo.GBFormatter(DeviceDiskInformation.usedDiskSpaceInBytes))
print("---MB---")
print(ByteInfo.MBFormatter(DeviceDiskInformation.totalDiskSpaceInBytes))
print(ByteInfo.MBFormatter(DeviceDiskInformation.freeDiskSpaceInBytes))
print(ByteInfo.MBFormatter(DeviceDiskInformation.usedDiskSpaceInBytes))
print("---KB---")
print(ByteInfo.KBFormatter(DeviceDiskInformation.totalDiskSpaceInBytes))
print(ByteInfo.KBFormatter(DeviceDiskInformation.freeDiskSpaceInBytes))
print(ByteInfo.KBFormatter(DeviceDiskInformation.usedDiskSpaceInBytes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment