- 一种受权利保护的数据容器,其中的数据会存储在 keychain 中。
- 配合 LARight 进行数据的存取,存取数据时需要经过用户授权。
- 需要导入
LocalAuthentication模块。
import LocalAuthentication
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Task {
let carID = "6270123456789000"
let data = carID.data(using: .utf8)
if let data {
try await storeData(data)
}
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
Task {
let data = try await fetchData()
if let data {
print(String(decoding: data, as: UTF8.self))
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
Task {
let loginRight = try await LARightStore.shared.right(forIdentifier: "bank-card")
await loginRight.deauthorize()
}
}
func storeData(_ data: Data) async throws {
let loginRight = LARight()
try await loginRight.authorize(localizedReason: "用户需要向keychain中存储敏感数据")
_ = try await LARightStore.shared.saveRight(loginRight, identifier: "bank-card", secret: data)
}
func fetchData() async throws -> Data {
let loginRight = try await LARightStore.shared.right(forIdentifier: "bank-card")
try await loginRight.authorize(localizedReason: "用户需要从keychain中获取敏感数据")
let data = try await loginRight.secret.rawData
return data
}
}