### Ruby: Carthage Installation for Cache Source: https://github.com/hyperoslo/cache/blob/master/README.md Provides instructions for installing the Cache library using Carthage. This involves adding the framework to the Cartfile and ensuring `SwiftHash.framework` is included in the build phases. ```ruby github "hyperoslo/Cache" ``` -------------------------------- ### Configuring Disk Storage with DiskConfig Source: https://github.com/hyperoslo/cache/blob/master/README.md Provides an example of configuring disk-based caching using `DiskConfig`. It shows how to set parameters such as the storage name, expiry duration, maximum size, custom directory, and data protection type. ```swift let diskConfig = DiskConfig( // The name of disk storage, this will be used as folder name within directory name: "Floppy", // Expiry date that will be applied by default for every added object // if it's not overridden in the `setObject(forKey:expiry:)` method expiry: .date(Date().addingTimeInterval(2*3600)), // Maximum size of the disk cache storage (in bytes) maxSize: 10000, // Where to store the disk cache. If nil, it is placed in `cachesDirectory` directory. directory: try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("MyPreferences"), // Data protection is used to store files in an encrypted format on disk and to decrypt them on demand protectionType: .complete ) ``` -------------------------------- ### Asynchronous Storage Operations with Callbacks in Swift Source: https://github.com/hyperoslo/cache/blob/master/README.md Demonstrates asynchronous storage operations using completion handlers (`Result`). This approach avoids blocking the current queue by delivering results later. It covers setting, getting, checking existence, and removing objects, handling success and failure cases within the callback. ```swift storage.async.setObject("Oslo", forKey: "my favorite city") { result in switch result { case .success: print("saved successfully") case .failure(let error): print(error) } } storage.async.object(forKey: "my favorite city") { result in switch result { case .success(let city): print("my favorite city is \(city)") case .failure(let error): print(error) } } storage.async.objectExists(forKey: "my favorite city") { result in if case .success(let exists) = result, exists { print("I have a favorite city") } } storage.async.removeAll() { result in switch result { case .success: print("removal completes") case .failure(let error): print(error) } } storage.async.removeExpiredObjects() { result in switch result { case .success: print("removal completes") case .failure(let error): print(error) } } ``` -------------------------------- ### Ruby: CocoaPods Installation for Cache Source: https://github.com/hyperoslo/cache/blob/master/README.md Specifies the command to add the Cache library to a project using CocoaPods. This involves adding a line to the project's Podfile, pointing to the Git repository for the latest version. ```ruby pod 'Cache', :git => 'https://github.com/hyperoslo/Cache.git' ``` -------------------------------- ### Synchronous Storage Operations in Swift Source: https://github.com/hyperoslo/cache/blob/master/README.md Demonstrates how to perform basic storage operations like setting, getting, checking existence, and removing objects synchronously using the StorageAware protocol. Handles various data types including integers, strings, arrays, and data. Errors are managed using Swift's try-catch mechanism. ```swift try? storage.setObject(10, forKey: "score") try? storage.setObject("Oslo", forKey: "my favorite city", expiry: .never) try? storage.setObject(["alert", "sounds", "badge"], forKey: "notifications") try? storage.setObject(data, forKey: "a bunch of bytes") try? storage.setObject(authorizeURL, forKey: "authorization URL") let score = try? storage.object(forKey: "score") let favoriteCharacter = try? storage.object(forKey: "my favorite city") let hasFavoriteCharacter = try? storage.objectExists(forKey: "my favorite city") try? storage.removeObject(forKey: "my favorite city") try? storage.removeAll() try? storage.removeExpiredObjects() ``` -------------------------------- ### Asynchronous Storage Operations with Swift Concurrency Source: https://github.com/hyperoslo/cache/blob/master/README.md Presents asynchronous storage operations using Swift's `async/await` syntax. This modern approach simplifies asynchronous code by allowing `try await` for operations like setting, getting, checking existence, and removing objects, with error handling via `do-catch` blocks. ```swift do { try await storage.async.setObject("Oslo", forKey: "my favorite city") print("saved successfully") } catch { print(error) } do { let city = try await storage.async.object(forKey: "my favorite city") print("my favorite city is \(city)") } catch { print(error) } do { let exists = try await storage.async.objectExists(forKey: "my favorite city") if exists { print("I have a favorite city") } } catch {} do { try await storage.async.remoeAll() print("removal completes") } catch { print(error) } do { try await storage.async.removeExpiredObjects() print("removal completes") } catch { print(error) } ``` -------------------------------- ### Implementing Try-Catch for Storage Initialization Source: https://github.com/hyperoslo/cache/blob/master/README.md Illustrates how to handle potential errors during the initialization of a `Storage` object using a `do-catch` block. This is crucial for managing issues that might arise from disk or configuration problems. ```swift do { let storage = try Storage(diskConfig: diskConfig, memoryConfig: memoryConfig) } catch { print(error) } ``` -------------------------------- ### Configuring Memory Cache with MemoryConfig Source: https://github.com/hyperoslo/cache/blob/master/README.md Demonstrates the configuration of an in-memory cache using `MemoryConfig`. Key parameters include expiry duration, the maximum number of objects the cache can hold, and the maximum total cost (size) before eviction. ```swift let memoryConfig = MemoryConfig( // Expiry date that will be applied by default for every added object // if it's not overridden in the `setObject(forKey:expiry:)` method expiry: .date(Date().addingTimeInterval(2*60)), /// The maximum number of objects in memory the cache should hold countLimit: 50, /// The maximum total cost that the cache can hold before it starts evicting objects totalCostLimit: 0 ) ``` -------------------------------- ### Swift: Configure and Initialize Cache Storage Source: https://github.com/hyperoslo/cache/blob/master/README.md This snippet demonstrates how to configure disk and memory storage settings and then initialize a `Storage` instance. It uses `DiskConfig` and `MemoryConfig` to define cache behavior, such as the disk cache name, memory expiry policy, and memory limits. The `TransformerFactory.forCodable` is used to specify that the cache will store `Codable` objects, in this case, of type `User`. ```swift let diskConfig = DiskConfig(name: "Floppy") let memoryConfig = MemoryConfig(expiry: .never, countLimit: 10, totalCostLimit: 10) let storage = try? Storage( diskConfig: diskConfig, memoryConfig: memoryConfig, transformer: TransformerFactory.forCodable(ofType: User.self) // Storage ) ``` -------------------------------- ### Swift: Alamofire with JSON Decoding and Storage Source: https://github.com/hyperoslo/cache/blob/master/README.md Demonstrates how to fetch JSON data using Alamofire, decode it into a Swift object using `JSONDecoder` extensions, and then store the object using the `Storage` library. This provides a complete workflow for handling backend JSON responses. ```swift Alamofire.request("https://gameofthrones.org/mostFavoriteCharacter").responseString { response in do { let user = try JSONDecoder.decode(response.result.success, to: User.self) try storage.setObject(user, forKey: "most favorite character") } catch { print(error) } } ``` -------------------------------- ### Retrieving Entry with Expiry and Meta in Swift Source: https://github.com/hyperoslo/cache/blob/master/README.md Shows how to retrieve an object along with its expiry information and metadata using the `entry` method. The `meta` property might contain file-specific details when using disk storage. This is useful for inspecting cache item details. ```swift let entry = try? storage.entry(forKey: "my favorite city") print(entry?.object) print(entry?.expiry) print(entry?.meta) ``` -------------------------------- ### Custom Codable Object Storage in Swift Source: https://github.com/hyperoslo/cache/blob/master/README.md Illustrates how to store custom `Codable` objects. It highlights that `[String: Any]` is not directly supported and recommends converting JSON responses to custom `Codable` structs before saving to storage to avoid runtime errors. ```swift struct User: Codable { let firstName: String let lastName: String } let user = User(fistName: "John", lastName: "Snow") try? storage.setObject(user, forKey: "character") ``` -------------------------------- ### Transforming Storage Types with Cache Source: https://github.com/hyperoslo/cache/blob/master/README.md Demonstrates how to use the `transform` function on a generic `Storage` object to create new storage instances with different type constraints. It shows transforming to `UIImage` and `String` types, emphasizing that the underlying caching mechanism remains the same while allowing type-specific operations. ```swift let storage: Storage = ... storage.setObject(superman, forKey: "user") let imageStorage = storage.transformImage() // Storage imageStorage.setObject(image, forKey: "image") let stringStorage = storage.transformCodable(ofType: String.self) // Storage stringStorage.setObject("hello world", forKey: "string") ``` -------------------------------- ### Swift: Observe Storage Changes Source: https://github.com/hyperoslo/cache/blob/master/README.md Adds an observer to the storage to monitor changes like additions, removals, and expirations. The observer is registered with a callback that handles different change cases. An observer token is returned, which can be used to cancel the observation. All observers can also be removed. ```swift let token = storage.addStorageObserver(self) { observer, storage, change in switch change { case .add(let key): print("Added \(key)") case .remove(let key): print("Removed \(key)") case .removeAll: print("Removed all") case .removeExpired: print("Removed expired") } } token.cancel() storage.removeAllStorageObservers() ``` -------------------------------- ### Swift: Observe Key-Specific Changes Source: https://github.com/hyperoslo/cache/blob/master/README.md Adds an observer for a specific key to monitor edits or removals of the associated value. This allows for granular tracking of changes related to a particular data entry. Observers can be cancelled using the returned token, or removed by key. All key observers can be cleared. ```swift let key = "user1" let token = storage.addObserver(self, forKey: key) { observer, storage, change in switch change { case .edit(let before, let after): print("Changed object for \(key) from \(String(describing: before)) to \(after)") case .remove: print("Removed \(key)") } } token.cancel() storage.removeObserver(forKey: key) storage.removeAllKeyObservers() ``` -------------------------------- ### Swift: Decode JSON to Objects Source: https://github.com/hyperoslo/cache/blob/master/README.md Provides extensions for `JSONDecoder` to decode JSON data from various formats (string, dictionary, data) into strongly typed Swift objects. This simplifies the process of converting backend responses into usable data models for UI display and storage. ```swift let user = JSONDecoder.decode(jsonString, to: User.self) let cities = JSONDecoder.decode(jsonDictionary, to: [City].self) let dragons = JSONDecoder.decode(jsonData, to: [Dragon].self) ``` -------------------------------- ### Setting Object Expiry in Swift Source: https://github.com/hyperoslo/cache/blob/master/README.md Demonstrates how to control the expiry date for individual objects stored in the cache. It shows setting a default expiry based on configuration and overriding it with a specific `Date` or `.never` for custom expiry policies. Includes a call to `removeExpiredObjects`. ```swift // Default expiry date from configuration will be applied to the item try? storage.setObject("This is a string", forKey: "string") // A given expiry date will be applied to the item try? storage.setObject( "This is a string", forKey: "string", expiry: .date(Date().addingTimeInterval(2 * 3600)) ) // Clear expired objects storage.removeExpiredObjects() ``` -------------------------------- ### StorageError Enum for Cache Operations Source: https://github.com/hyperoslo/cache/blob/master/README.md Defines the `StorageError` enum, which represents various error conditions that can occur during cache operations. This includes errors like `notFound`, `typeNotMatch`, `decodingFailed`, `encodingFailed`, and `transformerFail`, facilitating robust error handling. ```swift public enum StorageError: Error { /// Object can not be found case notFound /// Object is found, but casting to requested type failed case typeNotMatch /// The file attributes are malformed case malformedFileAttributes /// Can't perform Decode case decodingFailed /// Can't perform Encode case encodingFailed /// The storage has been deallocated case deallocated /// Fail to perform transformation to or from Data case transformerFail } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.