CloudUserDefaults automatically syncs UserDefaultsvalues that use a key with a specified prefix to the cloud. Silently listening to system events it detects when a UserDefaultskey 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.
About
CloudUserDefaults automatically syncs
UserDefaults
values that use a key with a specified prefix to the cloud. Silently listening to system events it detects when aUserDefaults
key with a given prefix is changed and automatically syncs the value. For example, if you choose cloud_ as the prefixUserDefaults.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 toMKiCloudSync
.Installation
Swift Package Manager
If you are using Xcode 11 or later:
File
Swift Packages
Add Package Dependency...
Manual
Copy
CloudUserDefaults.swift
to your projectSetup
In Xcode, click your project, click your target, click
Signing & Capabilities
, click+ Capability
, select iCloud. Check theKey-value storage
checkbox.NOTE iCloud events are not sent to the simulator.
Usage
Create an instance of
CloudUserDefaults
some place it will stay in scope (e.g. in yourAppDelegate
) and callstart
with a prefix of your choosing e.g.That’s it, whenever a
UserDefaults
key starts withcloud_
it is automatically synced to all the user’s devices e.g.Subscribe to
CloudUserDefaults.cloudSyncNotification
if you want to be notified when user defaults from another device are delivered e.g.Contributing
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.
License
MIT