How To Get Directory Size With Swift On OS X

前端 未结 5 1299
孤独总比滥情好
孤独总比滥情好 2020-12-15 13:04

I am trying to get the size of a directory, as well as it\'s content on OS X using Swift. So far, I have only been able to get the size of the directory itself, with none of

5条回答
  •  半阙折子戏
    2020-12-15 13:23

    Swift 3 version here:

     func findSize(path: String) throws -> UInt64 {
    
        let fullPath = (path as NSString).expandingTildeInPath
        let fileAttributes: NSDictionary = try FileManager.default.attributesOfItem(atPath: fullPath) as NSDictionary
    
        if fileAttributes.fileType() == "NSFileTypeRegular" {
            return fileAttributes.fileSize()
        }
    
        let url = NSURL(fileURLWithPath: fullPath)
        guard let directoryEnumerator = FileManager.default.enumerator(at: url as URL, includingPropertiesForKeys: [URLResourceKey.fileSizeKey], options: [.skipsHiddenFiles], errorHandler: nil) else { throw FileErrors.BadEnumeration }
    
        var total: UInt64 = 0
    
        for (index, object) in directoryEnumerator.enumerated() {
            guard let fileURL = object as? NSURL else { throw FileErrors.BadResource }
            var fileSizeResource: AnyObject?
            try fileURL.getResourceValue(&fileSizeResource, forKey: URLResourceKey.fileSizeKey)
            guard let fileSize = fileSizeResource as? NSNumber else { continue }
            total += fileSize.uint64Value
            if index % 1000 == 0 {
                print(".", terminator: "")
            }
        }
    
        if total < 1048576 {
            total = 1
        }
        else
        {
            total = UInt64(total / 1048576)
        }
    
        return total
    }
    
    enum FileErrors : ErrorType {
        case BadEnumeration
        case BadResource
    }
    

    Output value is megabyte. Converted from source: https://gist.github.com/rayfix/66b0a822648c87326645

提交回复
热议问题