Swiftchain 是一个完全使用 Swift 编写的轻量级 Keychain 包装器,旨在简化对安全存储形式的访问。
我可以在哪里使用它?
Swiftagram 支持 iOS、macOS、tvOS 和 watchOS。
下一步是什么?
非常欢迎 拉取请求。
请记住在贡献时参考我们的贡献指南 和 行为准则。
File
/Swift Packages
/Add Package Dependency…
。https://github.com/sbertix/Swifthcain.git
。为什么不使用 CocoaPods、Carthage 或
blank呢?
支持多种依赖管理器会使维护一个库的复杂性和耗时呈指数级增长。
此外,随着 Swift Package Manager 集成到 Xcode 11 及更高版本中,我们预计对替代解决方案的需求将迅速消退。
通过创建 Keychain
实例,服务名称会与安全存储在您设备钥匙串中的任何值相关联。如果您的 Bundle Identifier 存在,则默认为您的 Bundle Identifier;否则,默认为您可以预期在未来版本中不会更改的常量。
您可能需要在应用程序之间共享您的钥匙串项目:在这种情况下,只需在它们之间共享相同的访问组即可。
默认情况下,所有存储的项目只能在设备解锁时访问,但您可以在 init
初始化 Keychain
时,简单地选择自定义的 Keychain.Accessibility
(和授权)类型,以及 iCloud 同步规则:默认情况下,没有任何内容共享到云端。
请参考 Apple 官方 文档,以便更好地理解可访问性和身份验证之间的区别和用例。
如果我需要从后台访问我的钥匙串项目怎么办?
更改您的 accessibility
。 例如,您可以使用 .afterFirstUnlock
。
如果我需要确保设备已启用生物特征认证怎么办?
更改您的 authentication
。 例如,您可以使用 .biometryAny
。
// You can either call a shared instance…
var keychain = Keychain.default
// … or create your own!
keychain = Keychain(service: "com.sbertix.custom", // Optional.
group: "com.sbertix.group", // Optional.
accessibility: .afterFirstUnlock, // Optional.
authentication: .biometryAny, // Optional.
isSynchronizable: true) // Optional.
如何存储和检索项目?
您可以安全地存储和检索您想要的任何项目。 对类型、一致性等没有限制:我们在幕后为您处理所有这些!
let username: String = /* some String */
let password: String = /* some String */
// Store the password.
try? keychain.container(for: username).store(password)
/* later */
let container = keychain.container(for: username)
// Retrieve the password.
let secret = try? container.fetch(String.self)
// Or even simpler, if it's unambiguous.
let string: String? = try? container.fetch()
请记住,您不能在不先删除项目的情况下修改给定项目的可访问性或同步选项,但最简单的方法实际上是在 Container
之间复制或移动值。
// Another container, with some different synchronization or accessibility.
let anotherContainer: Container = /* some Container */
// Empty the container.
if let data = try? container.drop(Data.self) {
// Store it again…
try? anotherContainer.store(data)
}
/* or */
// Copy the content of `container` to `anotherContainer`.
try? container.copy(to: anotherContainer)
// Copy the content of `container` to `anotherContainer`, then erase `container`.
try? container.move(to: anotherContainer)
我可以覆盖默认的
Keychain
吗?
当然可以。
// Just set a new one.
Keychain.default = Keychain(accessibility: .afterFirstUnlock,
isSynchronizable: true)
特别感谢所有为 jrendel/SwiftKeychainWrapper 和 evgenyneu/keychain-swift 做出贡献的人,感谢他们的启发以及对开源社区的宝贵服务,没有这些,今天可能就不会有 Swiftchain。