本来这些在OC也可以实现,而且可以用桥接的方式来达到Swift使用,但是本着完全Swift 化的思想,还是想用纯Swift 方法来实现,以下是具体实现代码
给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
}
/// 将大小转换成字符串用以显示
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)
网友评论