[英]How to get the Total Disk Space and Free Disk space using AttributesOfFileSystemForpaths in swift 2.0
This is the way I use in Objective-C这是我在Objective-C中使用的方式
-(uint64_t)getFreeDiskspace {
float totalSpace = 0;
float totalFreeSpace = 0;
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
if (dictionary) {
NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
totalSpace = [fileSystemSizeInBytes floatValue];
self.totalSpace = [NSString stringWithFormat:@"%.3f GB",totalSpace/(1024*1024*1024)];
totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];
self.freeSpace = [NSString stringWithFormat:@"%.3f GB",totalFreeSpace/(1024*1024*1024)];
} else {
LogError(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
}
return totalFreeSpace;
} }
I tried converting it to swift and errors in我尝试将其转换为 swift 并出现错误
if(dictionary)
and和
attributesOfFileSystemForPaths
were shown.Can anyone help me in converting this to swift 2.0?已显示。任何人都可以帮助我将其转换为 swift 2.0 吗? It would do a world of good to my project.
它会对我的项目大有裨益。 Thank You in Advance.
先感谢您。
For Swift 5.1.3:对于 Swift 5.1.3:
struct FileManagerUility {
static func getFileSize(for key: FileAttributeKey) -> Int64? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
guard
let lastPath = paths.last,
let attributeDictionary = try? FileManager.default.attributesOfFileSystem(forPath: lastPath) else { return nil }
if let size = attributeDictionary[key] as? NSNumber {
return size.int64Value
} else {
return nil
}
}
static func convert(_ bytes: Int64, to units: ByteCountFormatter.Units = .useGB) -> String? {
let formatter = ByteCountFormatter()
formatter.allowedUnits = units
formatter.countStyle = ByteCountFormatter.CountStyle.decimal
formatter.includesUnit = false
return formatter.string(fromByteCount: bytes)
}
}
Use the api like this:像这样使用api:
if let totalSpaceInBytes = FileManagerUility.getFileSize(for: .systemSize) {
/// If you want to convert into GB then call like this
let totalSpaceInGB = FileManagerUility.convert(totalSpaceInBytes)
print("Total space [\(totalSpaceInBytes) bytes] = [\(totalSpaceInGB!) GB]")
}
if let freeSpaceInBytes = FileManagerUility.getFileSize(for: .systemFreeSize) {
/// If you want to convert into GB then call like this
let freeSpaceInGB = FileManagerUility.convert(freeSpaceInBytes)
print("Free space [\(freeSpaceInBytes) bytes] = [\(freeSpaceInGB!) GB]")
}
Update Swift 3 @ Md.Muzahidul Islam更新 Swift 3 @ Md.Muzahidul Islam
func getFreeSize() -> Int64? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) {
if let freeSize = dictionary[FileAttributeKey.systemFreeSize] as? NSNumber {
return freeSize.int64Value
}
}else{
print("Error Obtaining System Memory Info:")
}
return nil
}
func getTotalSize() -> Int64?{
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) {
if let freeSize = dictionary[FileAttributeKey.systemSize] as? NSNumber {
return freeSize.int64Value
}
}else{
print("Error Obtaining System Memory Info:")
}
return nil
}
func getFreeDiskspace() -> Int64? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let dictionary = try? FileManager.default.attributesOfFileSystem(forPath: paths.last!) {
if let freeSize = dictionary[FileAttributeKey.systemFreeSize] as? NSNumber {
return freeSize.int64Value
}
}else{
print("Error Obtaining System Memory Info:")
}
return nil
}
if let getFreespace = getFreeDiskspace() {
print(getFreespace) // free disk space
}
The technique in the other answers posted here do not work for me.此处发布的其他答案中的技术对我不起作用。 They return an amount of free space which is considerably lower than what I have available on my device.
他们返回的可用空间量大大低于我设备上的可用空间。 I believe the correct way of getting the amount of free space is by doing this:
我相信获得可用空间量的正确方法是这样做:
func deviceRemainingFreeSpaceInBytes() -> Int64? {
let url = URL(filePath: "/")
let results = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
return results?.volumeAvailableCapacityForImportantUsage
}
Taken from Apple's example here and converted to Swift. https://developer.apple.com/documentation/foundation/nsurlresourcekey/checking_volume_storage_capacity取自此处Apple的示例并转换为Swift。https://developer.apple.com/documentation/foundation/nsurlresourcekey/checking_volume_storage_capacity
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.