本來這些在OC也可以實現(xiàn)微服,而且可以用橋接的方式來達(dá)到Swift使用剖踊,但是本著完全Swift 化的思想脸秽,還是想用純Swift 方法來實現(xiàn)骂删,以下是具體實現(xiàn)代碼
給UIDevice 類寫了一個擴展
import UIKit
extension UIDevice{
func blankof<T>(type:T.Type) -> T {
let ptr = UnsafeMutablePointer<T>.allocate(capacity: MemoryLayout<T>.size)
let val = ptr.pointee
ptr.deinitialize()
return val
}
/// 磁盤總大小
var TotalDiskSize:Int64{
var fs = blankof(type: statfs.self)
if statfs("/var",&fs) >= 0{
return Int64(UInt64(fs.f_bsize) * fs.f_blocks)
}
return -1
}
/// 磁盤可用大小
var AvailableDiskSize:Int64{
var fs = blankof(type: statfs.self)
if statfs("/var",&fs) >= 0{
return Int64(UInt64(fs.f_bsize) * fs.f_bavail)
}
return -1
}
/// 將大小轉(zhuǎn)換成字符串用以顯示
func fileSizeToString(fileSize:Int64) -> String{
let fileSize1 = CGFloat(fileSize)
let KB:CGFloat = 1024
let MB:CGFloat = KB*KB
let GB:CGFloat = MB*KB
if fileSize < 10
{
return "0 B"
}else if fileSize1 < KB
{
return "< 1 KB"
}else if fileSize1 < MB
{
return String(format: "%.1f KB", CGFloat(fileSize1)/KB)
}else if fileSize1 < GB
{
return String(format: "%.1f MB", CGFloat(fileSize1)/MB)
}else
{
return String(format: "%.1f GB", CGFloat(fileSize1)/GB)
}
}
}
用的時候就比較簡單了
print(UIDevice.current.fileSizeToString(fileSize: UIDevice.current.AvailableDiskSize))
print(UIDevice.current.fileSizeToString(fileSize: UIDevice.current.TotalDiskSize))
print(UIDevice.current.AvailableDiskSize)
print(UIDevice.current.TotalDiskSize)