nbasham/clouduserdefaults
Just drop one file in your project and add a few lines of code and your settings are now visible to all your user's devices.
Installation
Swift Package Manager
1. Click File 2. Add Package Dependencies... 3. Specify the git URL for CloudUserDefaults.
https://github.com/nbasham/CloudUserDefaults.gitManual
Copy CloudUserDefaults.swift to your project
Setup
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.
NOTE On watchOS, NSUbiquitousKeyValueStore is not available prior to watchOS 9.0.
Usage
Create an instance of CloudUserDefaults somewhere it will stay in scope and call start with a prefix of your choosing.
AppDelegate
import CloudUserDefaults
...
let cloudUserDefaults = CloudUserDefaults()
cloudUserDefaults.start(prefix: "cloud_")SwiftUI
import CloudUserDefaults
@main
struct MyApp: App {
let cloudUserDefaults = CloudUserDefaults()
init() {
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)Advanced Usage
If you use app groups (e.g. to share defaults with a widget), pass your suite instead:
let suite = UserDefaults(suiteName: "group.com.mycompany.myapp")!
let cloudUserDefaults = CloudUserDefaults(defaults: suite)
cloudUserDefaults.start(prefix: "cloud_")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
Package Metadata
Repository: nbasham/clouduserdefaults
Default branch: main
README: README.md