简体   繁体   中英

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

-(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

if(dictionary)

and

attributesOfFileSystemForPaths 

were shown.Can anyone help me in converting this to swift 2.0? It would do a world of good to my project. Thank You in Advance.

For 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:

 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

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
    }

Update Swift-4

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM