How To Get Directory Size With Swift On OS X

前端 未结 5 1289
孤独总比滥情好
孤独总比滥情好 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:17

    For anyone looking for the barebones implementation (works the same on macOS and iOS):

    Swift 5 barebones version

    extension URL {
        var fileSize: Int? { // in bytes
            do {
                let val = try self.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey])
                return val.totalFileAllocatedSize ?? val.fileAllocatedSize
            } catch {
                print(error)
                return nil
            }
        }
    }
    
    extension FileManager {
        func directorySize(_ dir: URL) -> Int? { // in bytes
            if let enumerator = self.enumerator(at: dir, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .fileAllocatedSizeKey], options: [], errorHandler: { (_, error) -> Bool in
                print(error)
                return false
            }) {
                var bytes = 0
                for case let url as URL in enumerator {
                    bytes += url.fileSize ?? 0
                }
                return bytes
            } else {
                return nil
            }
        }
    }
    

    Usage

    let fm = FileManager.default
    let tmp = fm.temporaryDirectory
    
    if let size = fm.directorySize(tmp) {
        print(size)
    }
    

    What makes this barebones: doesn't precheck if a directory is a directory or a file is a file (returns nil either way), and the results are returned in their native format (bytes as integers).

提交回复
热议问题