手撸一个Flutter插件实现跨苹果全家桶云同步持久化Key Value数据( 二 )


写入保存一个Key的实现
class CKSaveValueHandler: CKCommandHandlerProtocol {var COMMAND_NAME: CKCommandType = .SAVE_VALUEfunc evaluateExecution(command: String) -> Bool {return CKCommandType(rawValue: command) == COMMAND_NAME}func handle(command: String, arguments: Dictionary, result: @escaping FlutterResult) {if (!evaluateExecution(command: command)) {return}if let key = arguments["key"] as? String, let value = http://www.kingceram.com/post/arguments["value"] as? String{let store = NSUbiquitousKeyValueStore.defaultstore.set(value, forKey: key)result(true)} else {result(FlutterError.init(code: "Error", message: "Cannot pass key and value parameter", details: nil))}}}
这里其实实现一下原生的通知监听,返回到就行,代码如下 。
let keyValueStore = NSUbiquitousKeyValueStore.default// 监听数据变化NotificationCenter.default.addObserver(self, selector: #selector(keyValueStoreDidChange), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: keyValueStore)keyValueStore.synchronize()@objc func keyValueStoreDidChange(notification: Notification) {// 处理数据变化if let userInfo = notification.userInfo as? [String: Any],let reasonForChange = userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] as? NSNumber {var reason = -1reason = reasonForChange.intValueif (reason == NSUbiquitousKeyValueStoreServerChange || reason == NSUbiquitousKeyValueStoreInitialSyncChange) {guard let changedKeys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] else {return}let store = NSUbiquitousKeyValueStore.defaultfor key in changedKeys {let value = http://www.kingceram.com/post/store.object(forKey: key)self.channel?.invokeMethod("icloud_key_update", arguments: [key:value])}}}}
上面一个一个的协议实现完毕,我们只需要扔到的协议方法里就可 。代码如下
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {let callArguments: Dictionary = call.arguments as! DictionaryCKGetValueHandler().handle(command: call.method, arguments: callArguments, result: result)CKSaveValueHandler().handle(command: call.method, arguments: callArguments, result: result)CKDeleteValueHandler().handle(command: call.method, arguments: callArguments, result: result)}
就这样一个支持跨苹果全家桶同步持久化Key Value数据的插件就完全了,是不是很简单呢?
用法
首先我们要在iOS或Mac项目开启 Key Value服务
然后导入享受它吧~
flutter pub add icloud_kv_storagedependencies:icloud_kv_storage: ^0.0.1
简单写法如下
import 'package:icloud_kv_storage/icloud_kv_storage.dart';var iCloudStorage = CKKVStorage();
A Key
void _incrementCounter() {setState(() {_counter++;iCloudStorage.writeString(key: key, value: _counter.toString());});}
Read A Key
iCloudStorage.getString('k_storage_count').then((value) {if (value != null) {setState(() {_counter = int.parse(value);});}});
A Key
void _clearCounter() {setState(() {_counter = 0;iCloudStorage.delete(key);});}
实时刷新
iCloudStorage.onCloudKitKVUpdateCallBack(onCallBack: (kvMap) {print('receive icloud_key_update map $kvMap');//if receive remove key will rec {flutter.k_storage_count: null}//if receive update key will rec {flutter.k_storage_count: 1}//because have prefix flutter. so need use my method to get real key.var key = iCloudStorage.getRealKey('k_storage_count');if (kvMap.containsKey(key)) {String? value = http://www.kingceram.com/post/kvMap[key];setState(() {if (value != null) {_counter =int.parse(kvMap[iCloudStorage.getRealKey('k_storage_count')]);} else {_counter = 0;}});}},);
下载地址
pub
结尾
【手撸一个Flutter插件实现跨苹果全家桶云同步持久化Key Value数据】