jsdw_ios/QuickLocation/Manager/App/AppCacheManager.swift

84 lines
2.9 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// AppCacheManager.swift
// QuickLocation
//
// Created by on 2026/6/11.
//
import Foundation
final class AppCacheManager {
// MARK: - ()
static func folderSize(at path: String) -> Int64 {
guard FileManager.default.fileExists(atPath: path) else { return 0 }
var totalSize: Int64 = 0
let manager = FileManager.default
guard let filePaths = try? manager.subpaths(atPath: path) else {
return totalSize
}
for subPath in filePaths {
let fullPath = path + "/" + subPath
var isDir: ObjCBool = false
if manager.fileExists(atPath: fullPath, isDirectory: &isDir) {
if isDir.boolValue {
totalSize += folderSize(at: fullPath)
} else {
//
if let attrs = try? manager.attributesOfItem(atPath: fullPath) {
totalSize += attrs[.size] as? Int64 ?? 0
}
}
}
}
return totalSize
}
// MARK: - App Caches + tmp
static func totalCacheSize() -> Int64 {
let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? ""
let tmpPath = NSTemporaryDirectory()
let cachesSize = folderSize(at: cachesPath)
let tmpSize = folderSize(at: tmpPath)
return cachesSize + tmpSize
}
// MARK: - B/KB/MB/GB
static func formatByte(_ byte: Int64) -> String {
guard byte > 0 else { return "0 B" }
let units: [String] = ["B", "KB", "M", "G"]
var size = Double(byte)
var unitIndex = 0
while size >= 1024, unitIndex < units.count - 1 {
size /= 1024
unitIndex += 1
}
return String(format: "%.2f %@", size, units[unitIndex])
}
// MARK: - Caches + tmp
static func clearCache(completion: @escaping () -> Void) {
DispatchQueue.global(qos: .background).async {
let manager = FileManager.default
// Caches
let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? ""
try? manager.removeItem(atPath: cachesPath)
try? manager.createDirectory(atPath: cachesPath, withIntermediateDirectories: true)
// tmp
let tmpPath = NSTemporaryDirectory()
let tmpFiles = (try? manager.contentsOfDirectory(atPath: tmpPath)) ?? []
tmpFiles.forEach { file in
try? manager.removeItem(atPath: tmpPath + file)
}
DispatchQueue.main.async {
completion()
}
}
}
}