### iCloudKV Shared Key for Double Values in Swift Source: https://context7.com/kthkuang/sharing-cloud/llms.txt This example showcases how to leverage SharingCloud with iCloudKV for synchronizing double-precision floating-point numbers across devices. It uses the `@Shared` property wrapper for seamless data persistence. Required frameworks are SharingCloud and SwiftUI. The method takes a key string and a default double value, producing a synced double property. ```swift import SharingCloud import SwiftUI struct VolumeSettingsView: View { @Shared(.iCloudKV("volume")) private var volume: Double = 0.5 @Shared(.iCloudKV("brightness")) private var brightness: Double = 0.75 var body: some View { VStack { Slider(value: $volume, in: 0...1) { Text("Volume: \(volume, specifier: \"%.2f\")") } Slider(value: $brightness, in: 0...1) { Text("Brightness: \(brightness, specifier: \"%.2f\")") } } .padding() } } // Settings persist and sync across all devices ``` -------------------------------- ### iCloudKV Shared Key for Integer Values in Swift Source: https://context7.com/kthkuang/sharing-cloud/llms.txt This code example shows how to use SharingCloud to create a shared key for integer values, enabling synchronization of integers across devices using iCloud key-value storage. The `@Shared` property wrapper is employed for this purpose. It requires SharingCloud and SwiftUI frameworks. The function accepts a key string and a default integer, outputting a synced integer property. ```swift import SharingCloud import SwiftUI struct FontSettingsView: View { @Shared(.iCloudKV("fontSize")) private var fontSize: Int = 14 var body: some View { VStack { Text("Sample Text") .font(.system(size: CGFloat(fontSize))) Stepper("Font Size: \(fontSize)", value: $fontSize, in: 10...30) .padding() } } } // Changes sync across all user's devices automatically ``` -------------------------------- ### Basic iCloud KV Synchronization with @Shared Property Wrapper Source: https://github.com/kthkuang/sharing-cloud/blob/main/README.md Demonstrates how to use the @Shared property wrapper with the .iCloudKV storage strategy to synchronize primitive types (Bool, Int) across devices. This requires importing SharingCloud and is suitable for use within ObservableObject or @Observable classes and SwiftUI views. ```swift import SharingCloud // In an ObservableObject or @Observable class @Observable class SettingsModel { @ObservationIgnored @Shared(.iCloudKV("userPreferences")) var isDarkModeEnabled: Bool = false @ObservationIgnored @Shared(.iCloudKV("notificationsEnabled")) var notificationsEnabled: Bool = true @ObservationIgnored @Shared(.iCloudKV("fontSize")) var fontSize: Int = 14 } // In a SwiftUI view struct SettingsView: View { @Shared(.iCloudKV("userPreferences")) private var isDarkModeEnabled: Bool = false @Shared(.iCloudKV("notificationsEnabled")) private var notificationsEnabled: Bool = true @Shared(.iCloudKV("fontSize")) private var fontSize: Int = 14 var body: some View { Form { Toggle("Dark Mode", isOn: $isDarkModeEnabled) Toggle("Notifications", isOn: $notificationsEnabled) Stepper("Font Size: \(fontSize)", value: $fontSize, in: 10...30) } } } ``` -------------------------------- ### SwiftUI View for Synchronizing Optional iCloudKV Values Source: https://context7.com/kthkuang/sharing-cloud/llms.txt Demonstrates a SwiftUI view that uses @Shared with iCloudKV to synchronize optional String, Int, and Bool values. It allows setting, clearing, and toggling these values, with changes reflected across devices. Dependencies include SharingCloud and SwiftUI. ```swift import SharingCloud import SwiftUI struct OptionalSettingsView: View { @Shared(.iCloudKV("optionalName")) private var name: String? = nil @Shared(.iCloudKV("optionalAge")) private var age: Int? = nil @Shared(.iCloudKV("optionalEnabled")) private var isEnabled: Bool? = nil var body: some View { Form { Section("Optional String") { if let name = name { Text("Name: \(name)") Button("Clear Name") { self.name = nil } } else { Button("Set Name") { name = "John Doe" } } } Section("Optional Int") { if let age = age { Text("Age: \(age)") Button("Clear Age") { self.age = nil } } else { Button("Set Age") { age = 25 } } } Section("Optional Bool") { if let isEnabled = isEnabled { Toggle("Feature Enabled", isOn: Binding( get: { isEnabled }, set: { self.isEnabled = $0 } )) } else { Button("Initialize") { isEnabled = true } } } } } } // Optional values can be set, updated, or cleared across devices ``` -------------------------------- ### iCloudKVKey for iCloud Key-Value Store Persistence Source: https://context7.com/kthkuang/sharing-cloud/llms.txt Illustrates the core iCloudKVKey structure used for iCloud key-value store persistence with SharingCloud. It handles loading, saving, synchronization, and change detection for keys. This structure is typically accessed via the @Shared property wrapper. Dependencies include SharingCloud, Sharing, and Foundation. ```swift import SharingCloud import Sharing import Foundation // Direct initialization (typically not needed - use .iCloudKV() instead) let boolKey = iCloudKVKey("myBoolKey") let intKey = iCloudKVKey("myIntKey") // The key provides unique identification let keyID = boolKey.id // iCloudKVKeyID // Key validation - automatically checks length let longKey = iCloudKVKey("thisIsAVeryLongKeyNameThatExceedsTheSixtyFourByteLimit_ExtraChars") // Triggers reportIssue: "The maximum length for key strings for the iCloud key-value store is 64 bytes..." // Typical usage through SharedReaderKey extension @Shared(.iCloudKV("counter")) var counter: Int = 0 // The iCloudKVKey handles: // - Loading values from NSUbiquitousKeyValueStore // - Subscribing to external iCloud changes // - Saving values with synchronization // - Automatic foreground refresh // - Quota violation detection // - Entitlement validation // Thread-safe access with automatic UI updates counter += 1 // Automatically saves and syncs to iCloud ``` -------------------------------- ### Mutex Synchronization Primitive for Thread Safety Source: https://context7.com/kthkuang/sharing-cloud/llms.txt Presents the Mutex struct, a thread-safe synchronization primitive for protecting shared mutable state using mutual exclusion. It's backported for wider platform availability and used internally by iCloudKVKey for thread-safe value tracking. It supports operations like incrementing and setting values with locking mechanisms. Dependencies include Foundation. ```swift import Foundation // Internal usage in iCloudKVKey for thread-safe value tracking struct ValueCache { private let mutex: Mutex init(initialValue: Int) { mutex = Mutex(initialValue) } func increment() -> Int { mutex.withLock { value in value += 1 return value } } func getValue() -> Int { mutex.withLock { $0 } } func setValue(_ newValue: Int) { mutex.withLock { $0 = newValue } } } // Usage example let cache = ValueCache(initialValue: 0) print(cache.increment()) // 1 print(cache.increment()) // 2 cache.setValue(10) print(cache.getValue()) // 10 // Error handling with withLock enum CacheError: Error { case invalidValue } let safeMutex = Mutex(nil) let result = try? safeMutex.withLock { value in guard let unwrapped = value else { throw CacheError.invalidValue } return unwrapped.count } ``` -------------------------------- ### iCloudKV Shared Key for Boolean Values in Swift Source: https://context7.com/kthkuang/sharing-cloud/llms.txt This snippet demonstrates how to create a shared key for boolean values using SharingCloud's iCloudKV functionality. It utilizes the `@Shared` property wrapper to sync boolean data across devices via iCloud's key-value store. Dependencies include SharingCloud and SwiftUI. It takes a key string and a default boolean value as input and outputs a synced boolean property. ```swift import SharingCloud import SwiftUI @Observable class SettingsModel { @ObservationIgnored @Shared(.iCloudKV("darkModeEnabled")) var isDarkModeEnabled: Bool = false } struct SettingsView: View { @Shared(.iCloudKV("darkModeEnabled")) private var isDarkModeEnabled: Bool = false var body: some View { Toggle("Enable Dark Mode", isOn: $isDarkModeEnabled) .padding() } } // Value automatically syncs to iCloud and updates on all devices ``` -------------------------------- ### iCloudKV Shared Key for URL Values (Swift) Source: https://context7.com/kthkuang/sharing-cloud/llms.txt Synchronizes URL values to iCloud Key-Value Store by storing them as strings internally. It utilizes the @Shared property wrapper for seamless integration. ```swift import SharingCloud import SwiftUI struct BookmarkView: View { @Shared(.iCloudKV("lastVisitedURL")) private var lastURL: URL? = nil @State private var urlString: String = "" var body: some View { VStack { if let url = lastURL { Text("Last visited: (url.absoluteString)") .padding() } TextField("Enter URL", text: $urlString) .textFieldStyle(.roundedBorder) .padding() Button("Save URL") { if let url = URL(string: urlString) { lastURL = url } } } } } // URLs sync across devices for quick access ``` -------------------------------- ### iCloudKV Shared Key for Data Values (Swift) Source: https://context7.com/kthkuang/sharing-cloud/llms.txt Synchronizes binary Data values to iCloud Key-Value Store with a per-key limit of 1MB. It includes a function to save data, retrieve it, and clear the cache. ```swift import SharingCloud import Foundation struct DataSyncManager { @Shared(.iCloudKV("cachedData")) private var cachedData: Data? = nil func saveSmallFile(_ data: Data) throws { guard data.count <= 1_000_000 else { throw NSError(domain: "DataTooLarge", code: 1) } cachedData = data } func loadCachedData() -> Data? { return cachedData } func clearCache() { cachedData = nil } } // Usage let manager = DataSyncManager() // Save data (automatically syncs to iCloud) let sampleData = "Important data".data(using: .utf8)! try? manager.saveSmallFile(sampleData) // Retrieve data (from local cache or iCloud) if let data = manager.loadCachedData() { print("Retrieved: \(String(data: data, encoding: .utf8) ?? "nil")") } ``` -------------------------------- ### iCloudKV Shared Key for RawRepresentable Enums (Swift) Source: https://context7.com/kthkuang/sharing-cloud/llms.txt Synchronizes RawRepresentable enums (with Int or String raw values) to iCloud Key-Value Store. It uses the @Shared property wrapper with the iCloudKV initializer. ```swift import SharingCloud import SwiftUI enum Theme: String, Sendable { case light case dark case system } enum NotificationFrequency: Int, Sendable { case never = 0 case daily = 1 case weekly = 7 case monthly = 30 } struct AppSettingsView: View { @Shared(.iCloudKV("appTheme")) private var theme: Theme = .system @Shared(.iCloudKV("notificationFrequency")) private var frequency: NotificationFrequency = .daily var body: some View { Form { Picker("Theme", selection: $theme) { Text("Light").tag(Theme.light) Text("Dark").tag(Theme.dark) Text("System").tag(Theme.system) } Picker("Notifications", selection: $frequency) { Text("Never").tag(NotificationFrequency.never) Text("Daily").tag(NotificationFrequency.daily) Text("Weekly").tag(NotificationFrequency.weekly) Text("Monthly").tag(NotificationFrequency.monthly) } } } } // Enum values are stored as raw values and synced across devices ``` -------------------------------- ### iCloudKV Shared Key for String Values in Swift Source: https://context7.com/kthkuang/sharing-cloud/llms.txt This Swift snippet illustrates the use of SharingCloud's iCloudKV to manage shared string values, facilitating text synchronization across multiple devices via iCloud. The `@Shared` property wrapper is central to this functionality. It depends on SharingCloud and SwiftUI. The input is a key string and a default string value, resulting in a synced string property. ```swift import SharingCloud import SwiftUI struct UserProfileView: View { @Shared(.iCloudKV("userName")) private var userName: String = "Guest" @Shared(.iCloudKV("userBio")) private var userBio: String = "" var body: some View { Form { TextField("Name", text: $userName) TextEditor(text: $userBio) .frame(height: 100) } .navigationTitle("Profile") } } // User profile data syncs seamlessly across devices ``` -------------------------------- ### Storing Complex Types (URL) with iCloud KV Source: https://github.com/kthkuang/sharing-cloud/blob/main/README.md Shows how to synchronize complex data types, specifically a URL, using the @Shared property wrapper with the .iCloudKV storage strategy. This demonstrates the library's support for types beyond simple primitives. ```swift @Shared(.iCloudKV("lastVisitedURL")) var lastURL: URL? ``` -------------------------------- ### iCloudKV Shared Key for Date Values (Swift) Source: https://context7.com/kthkuang/sharing-cloud/llms.txt Synchronizes Date values to iCloud Key-Value Store for timestamp synchronization across devices. It uses the @Shared property wrapper to manage the shared date properties. ```swift import SharingCloud import SwiftUI struct LastActivityView: View { @Shared(.iCloudKV("lastAppLaunch")) private var lastLaunch: Date? = nil @Shared(.iCloudKV("lastSyncTime")) private var lastSync: Date = Date() var body: some View { VStack(spacing: 20) { if let launch = lastLaunch { Text("Last opened: \(launch.formatted())") } Text("Last synced: \(lastSync.formatted())") Button("Update Launch Time") { lastLaunch = Date() } Button("Sync Now") { lastSync = Date() } } .padding() .onAppear { if lastLaunch == nil { lastLaunch = Date() } } } } // Timestamps sync across devices for activity tracking ``` -------------------------------- ### iCloud KV Synchronization with RawRepresentable Types Source: https://github.com/kthkuang/sharing-cloud/blob/main/README.md Illustrates storing custom RawRepresentable types (like enums with String raw values) using the @Shared property wrapper and the .iCloudKV storage strategy. This allows for structured synchronization of custom settings across devices. ```swift enum Theme: String, Sendable { case light case dark case system } struct ThemeSettingsView: View { @Shared(.iCloudKV("appTheme")) private var theme: Theme = .system var body: some View { Picker("Theme", selection: $theme) { Text("Light").tag(Theme.light) Text("Dark").tag(Theme.dark) Text("System").tag(Theme.system) } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.