1. 需要通过指纹,面容认证后才能打开 App
2. 添加配置
需要向 Info.plist 文件中添加一个配置,向用户说明为什么要访问
添加 Privacy - Face ID Usage Description
并为其赋予值 $(PRODUCT_NAME) need Touch Id or Face ID permission for app lock
3. Show me the code
//
// SwiftUIView84.swift
// bill2
//
// Created by 朱洪苇 on 2023/7/22.
//
import SwiftUI
import LocalAuthentication
struct SwiftUIView84: View {
@State private var isUnlocked = false
func authenticate() {
let context = LAContext()
var error: NSError?
// 检查是否可以进行生物特征认证
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
// 有可能,所以继续使用它
let reason = "We need to unlock your data."
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
// 身份验证现已完成
DispatchQueue.main.async {
if success {
// authenticated successfully
self.isUnlocked = true
print("成功认证")
} else {
// there was a problem
self.isUnlocked = false
print("有个问题")
}
}
}
} else {
print("没有生物识别")
// 没有生物识别
}
}
var body: some View {
VStack {
if self.isUnlocked {
Text("Unlocked")
.foregroundColor(.green)
} else {
Text("Locked")
.foregroundColor(.red)
}
}
.font(.largeTitle)
.onAppear(perform: authenticate)
}
}
struct SwiftUIView84_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView84()
}
}
4. 真机运行