CloudUserDefaults automatically syncs UserDefaults values that use a key with a specified prefix to the cloud. Silently listening to system events it detects when a UserDefaults key with a given prefix is changed and automatically syncs the value. For example, if you choose cloud_ as the prefix UserDefaults.standard.set(1, forKey: "cloud_count") is set on all the user's devices.
This is based on Mugunth Kumar's elegant solution MKiCloudSync an Objective-C GitHub repository that is now archived. Thanks to Paul Hudson for the introduction to MKiCloudSync.
If you are using Xcode 11 or later:
- Click
File Swift PackagesAdd Package Dependency...- Specify the git URL for CloudUserDefaults.
https://github.com/nbasham/CloudUserDefaults.gitCopy CloudUserDefaults.swift to your project
In Xcode, click your project, click your target, click Signing & Capabilities, click + Capability, select iCloud. Check the Key-value storage checkbox.
NOTE iCloud events are not sent to the simulator.
Create an instance of CloudUserDefaults some place it will stay in scope (e.g. in your AppDelegate) and call start with a prefix of your choosing e.g.
import CloudUserDefaults
...
let cloudUserDefaults = CloudUserDefaults()
cloudUserDefaults.start(prefix: "cloud_")That's it, whenever a UserDefaults key starts with cloud_ it is automatically synced to all the user's devices e.g.
UserDefaults.standard.set(42, forKey: "cloud_answer") // synced to cloud
UserDefaults.standard.set(42, forKey: "answer") // localSubscribe to CloudUserDefaults.cloudSyncNotification if you want to be notified when user defaults from another device are delivered e.g.
NotificationCenter.default.addObserver(self,
selector: #selector(cloudUpdate(notification:)),
name: CloudUserDefaults.cloudSyncNotification,
object: nil)Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.