iOS16新特性之LARightStore

2022-06-12 16:47:21 浏览数 (1)

  • 一种受权利保护的数据容器,其中的数据会存储在 keychain 中。
  • 配合 LARight 进行数据的存取,存取数据时需要经过用户授权。
  • 需要导入LocalAuthentication模块。
代码语言:javascript复制
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()
        }
    }

    // MARK: 存储数据
    func storeData(_ data: Data) async throws {
        // 1. 创建LARight
        let loginRight = LARight()
        // 2. 请求授权,弹出验证信息,通过TouchID、FaceID或密码验证
        try await loginRight.authorize(localizedReason: "用户需要向keychain中存储敏感数据")
        // 3. 存储数据
        _ = try await LARightStore.shared.saveRight(loginRight, identifier: "bank-card", secret: data)
    }

    // MARK: 读取数据
    func fetchData() async throws -> Data {
        // 1. 获取LARight
        let loginRight = try await LARightStore.shared.right(forIdentifier: "bank-card")
        // 2. 请求授权
        try await loginRight.authorize(localizedReason: "用户需要从keychain中获取敏感数据")
        // 3. 获取数据
        let data = try await loginRight.secret.rawData
        return data
    }
}

0 人点赞