SwiftSimpleCloudStore 库

GitHub

一个开源库,它为 NSUbiquitousKeyValueStore 提供了一个包装器,用于访问云同步的简单存储。

作为 XII 的 iOS、macOS 和 watchOS 应用程序中各种项目的可重用组件而开发。

安装

Swift Package Manager

  1. 在 Xcode 中,选择 File > Swift Packages > Add Package Dependency。
  2. 按照提示使用此仓库的 URL
  3. 选择 SwiftSimpleCloudStore 库添加到您的项目

依赖项

许可证

请参阅 LICENSE 文件。

SimpleCloudStore 服务 (源代码)

class SimpleCloudStore {
  static let DEFAULT_LOG_LEVEL: OSLogType = .info

  init(logLevel: OSLogType = DEFAULT_LOG_LEVEL)

  func synchronize()

  func getArray<Element>(
    forKey: String,
    defaultValue: [Element]
  ) -> [Element]

  func getBool(forKey: String) -> Bool

  func getData(
    forKey: String,
    defaultValue: Data
  ) -> Data

  func getDictionary<Value>(
    forKey: String,
    defaultValue: [String: Value]
  ) -> [String: Value]

  func getDouble(forKey: String) -> Double

  func getInt(forKey: String) -> Int

  func getSet<Element>(
    forKey: String,
    defaultValue: Set<Element>
  ) -> Set<Element>

  func getString(
    forKey: String,
    defaultValue: String
  ) -> String

  func set<Element>(forKey: String, value: Array<Element>)

  func set(forKey: String, value: Bool)

  func set(forKey: String, value: Data)

  func set<Value>(forKey: String, value: [String: Value])

  func set(forKey: String, value: Double)

  func set(forKey: String, value: Int)

  func set<Element>(forKey: String, value: Set<Element>)

  func set(forKey: String, value: String)

  func clear(forKey: String)
}

NSUbiquitousKeyValueStore 的包装器,为设置/读取/清除存储的值提供简写。

synchronize 函数将内存中的存储与其存储状态(以及可能的云状态)同步。此函数应在应用程序启动期间以及应用程序返回前台时调用一次。

将存储添加到您的环境 (源代码)

SimpleCloudServiceProvider 协议

protocol SimpleCloudStoreProvider {
  var store: SimpleCloudStore { get }
}

定义一个可以返回 SimpleCloudService 实例的提供程序。

通过此提供程序协议使用对存储的间接访问,以防止在 EnvironmentValues 中初始化多个存储。

两个提供程序实现可用

struct UnavailableSimpleCloudStoreProvider : SimpleCloudStoreProvider { }

SimpleCloudStoreProvider 的一个实现,当没有 SimpleCloudStore 可用时使用。

如果请求存储,则引发 fatalError


struct StaticSimpleCloudStoreProvider : SimpleCloudStoreProvider { }

SimpleCloudStoreProvider 的一个实现,它返回初始化期间提供的 SimpleCloudStore 实例。

通过 View 扩展提供实例

extension View {
  func simpleCloudStoreProvider(_ provider: SimpleCloudStoreProvider) -> some View

  func simpleCloudStore(_ store: SimpleCloudStore) -> some View
}

在您的 View 中检索实例

struct FooView : View {
  @Environment(\.simpleCloudStoreProvider) private var simpleCloudStoreProvider

  var body : some View {
    Test("Bar")
      .onAppear {
        let value = simpleCloudStoreProvider.store
          .getBool(forKey: "someKey")

        print("Value: \(value))
      }
  }
}