How To Get Directory Size With Swift On OS X

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

    To anyone who is looking for a solution for Swift 5+ and Xcode 11+ look at this gist

    func directorySize(url: URL) -> Int64 {
        let contents: [URL]
        do {
            contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey])
        } catch {
            return 0
        }
    
        var size: Int64 = 0
    
        for url in contents {
            let isDirectoryResourceValue: URLResourceValues
            do {
                isDirectoryResourceValue = try url.resourceValues(forKeys: [.isDirectoryKey])
            } catch {
                continue
            }
    
            if isDirectoryResourceValue.isDirectory == true {
                size += directorySize(url: url)
            } else {
                let fileSizeResourceValue: URLResourceValues
                do {
                    fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey])
                } catch {
                    continue
                }
    
                size += Int64(fileSizeResourceValue.fileSize ?? 0)
            }
        }
        return size
    

    }

提交回复
热议问题