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

后端 未结 18 2055
别跟我提以往
别跟我提以往 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:42

    for Swift as UIDevice extension

    extension UIDevice {
        func freeDiskspace() -> NSString {
            let failedResult: String = "Error Obtaining System Memory"
            guard let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last else {
                return failedResult
            }
            do {
                let dictionary = try NSFileManager.defaultManager().attributesOfFileSystemForPath(path)
                if let fileSystemSizeInBytes = dictionary[NSFileSystemSize] as? UInt,
                    let freeFileSystemSizeInBytes =     dictionary[NSFileSystemFreeSize] as? UInt {
                        return "Memory \(freeFileSystemSizeInBytes/1024/1024) of \(fileSystemSizeInBytes/1024/1024) Mb available."
                } else {
                        return failedResult
                }
            } catch {
                return failedResult
            }
        }
    }
    

    How to use:

    print("\(UIDevice.currentDevice().freeDiskspace())")
    

    Output will be:

    Memory 9656 of 207694 Mb available.
    

提交回复
热议问题