Sobes.tech
Middle

How can data caching be implemented using only your own tools, without third-party libraries?

sobes.tech AI

Answer from AI

Using URLCache for HTTP/HTTPS requests, FileManager for file caching, and UserDefaults for small, simple data.

// Example with URLCache
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData // Example policy
let session = URLSession(configuration: configuration)

let url = URL(string: "https://example.com/api/data")!
let task = session.dataTask(with: url) { data, response, error in
    // Data handling
}
task.resume()
// Example with FileManager (caching data to a file)
let fileManager = FileManager.default
let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!
let fileURL = cacheDirectory.appendingPathComponent("cached_data.txt")

// Writing data
let dataToCache = "Some cached data".data(using: .utf8)!
do {
    try dataToCache.write(to: fileURL)
} catch {
    print("Error writing to file: \(error)")
}

// Reading data
do {
    let cachedData = try Data(contentsOf: fileURL)
    let cachedString = String(data: cachedData, encoding: .utf8)
    print("Cached data: \(cachedString ?? "nil")")
} catch {
    print("Error reading file: \(error)")
}
// Example with UserDefaults (caching simple data)
let defaults = UserDefaults.standard

// Writing data
defaults.set("cached_value", forKey: "myCachedKey")

// Reading data
let cachedValue = defaults.string(forKey: "myCachedKey")
print("Cached value from UserDefaults: \(cachedValue ?? "nil")")
How can data caching be implemented using only your… - sobes.tech