iCloud > Key-Value Storage 使い方
初期化
swift
storage = NSUbiquitousKeyValueStore()
prop1 = storage.double(forKey: "prop1") // シリアライズしたデータの場合は .data()
storage.syncronize()
値の変更を通知
swift
storage.set(value, forKey: "prop1")
storage.synchronize()
値の変更通知を受け取る
swift
func valueReceived() async {
let center = NotificationCenter.default
let name = NSUbiquitousKeyValueStore.didChangeExternallyNotification
for await notification in center.notifications(named: name, object: storage) {
if notification.name == name {
await MainActor.run {
prop1 = storage.double(forKey: "prop1")
}
}
}
}
View 側からはこのように
swift
...
.task {
await appData.valueReceived()
}