Post

Replies

Boosts

Views

Activity

Reply to caches directory counts towards app storage?
i've created an app that measures the cache directory, and has a button to write 10MB of random data into the caches directory after installing the app, documents and data say 0 after hitting the write to cache button in the app, documents and data reports count(button_tap)*10 MB. this is the buggy behavior. it should still report 0MB // // ContentView.swift // cache-example // // Created by Andrew Breckenridge on 12/4/24. // import SwiftUI struct ContentView: View { @State private var cacheSize: String = "Cache Size: 0 MB" var body: some View { VStack(spacing: 20) { Text(cacheSize) .font(.system(size: 22, weight: .medium)) Button(action: writeRandomDataToCache) { Text("Write 10MB to Cache") .padding() .background(Color.gray) .foregroundColor(.white) .cornerRadius(8) } } .padding() .onAppear(perform: updateCacheSize) } private func writeRandomDataToCache() { let data = Data(count: 10 * 1024 * 1024) // 10MB of random data if let cacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first { let fileURL = cacheDirectory.appendingPathComponent(UUID().uuidString) do { try data.write(to: fileURL) updateCacheSize() } catch { print("Error writing data to cache: \(error)") } } } private func updateCacheSize() { if let cacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first { do { let files = try FileManager.default.contentsOfDirectory(at: cacheDirectory, includingPropertiesForKeys: [.fileSizeKey], options: .skipsHiddenFiles) let totalSize = files.reduce(0) { (result, fileURL) -> Int in let fileSize = (try? fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0 return result + fileSize } cacheSize = "Cache Size: \(totalSize / (1024 * 1024)) MB" } catch { print("Error calculating cache size: \(error)") } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Dec ’24