我试图在应用程序进入后台时锁定我的应用程序,当应用程序在前台时,用户可以使用生物识别(FaceID/TouchID)身份验证解锁应用程序。
这是我的代码的一个简单、可重现的示例:
import LocalAuthentication
import SwiftUI
struct ContentView: View {
@State var isUnlocked = false
var body: some View {
if isUnlocked {
// if the app is unlocked, app shows the text "Unlocked"
Text("Unlocked")
.font(.title)
// app gets locked when the app goes to background
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
self.isUnlocked = false
print("locked the app")
}
} else {
// if the app is locked, app shows the text "Locked" and app should show prompt FaceID/TouchID prompt
Text("LOCKED")
.font(.title)
// FaceID prompt shows when the app opens (from Non-running state)
.onAppear(perform: authenticate)
// FaceID prompt shows when the app coming from background to foreground
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
authenticate()
print("back inside the app")
}
}
}
// I use this to prompt the biometric authentication
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 {
// app gets unlocked if biometrix authentication succeeded
self.isUnlocked = true
} else {
// authentication failed
}
}
}
} else {
// no biometrics
}
}
}
当用户打开应用程序(从非运行状态)时,FaceID 提示会立即显示,不会有任何延迟。但是当应用程序从后台转到前台时,FaceID 提示大约需要 5 秒才能显示出来。当应用程序从后台转到前台时,我使用相同的功能authenticate()
来提示生物识别身份验证和 Xcode 控制台打印。那么导致 FaceID 延迟的原因是什么?"back inside the app"
请帮我。谢谢。