(Q)如何在SwiftUI中使用按钮动作

时间:2020-04-04 08:44:34

标签: swift swiftui

我目前正在使用Swift UI创建一个支持FaceID的应用程序。 我要尝试的是在用户按下按钮时尝试FaceID身份验证。当我在按钮操作中调用类时,出现错误消息“'DashboardView'初始化程序的结果未使用”。相关资料如下。任何帮助将不胜感激!

        struct FaceLoginView: View {

        @State private var isUnlocked = false

        var body: some View {
            VStack {

                Button(action: {
                   print("face id tapped!")

                        if self.isUnlocked {
                                 // print("unlocked")
                            DashboardView()
                        } else {
                                // Text("Locked")
                            LoginView()
                        }
                }) {
                    HStack {
                        Image(systemName: "faceid")
                            .font(.title)
                        Text("faceid")
                            .fontWeight(.semibold)
                            .font(.title)
                    }
                    .frame(minWidth: 0, maxWidth: .infinity)
                    .padding()
                    .foregroundColor(.white)
                    .background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
                    .cornerRadius(40)
                }
            }
            .onAppear(perform: authenticate)
        }

        func authenticate() {
            let context = LAContext()
            var error: NSError?

            if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
                let reason = "Log in to your account by unlocking FaceID."
                context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
                    DispatchQueue.main.async {
                        if success {
                            // authenticated successfully
                            self.isUnlocked = true
                        } else {
                            // there was a problem
                            self.isUnlocked = false
                            print(error?.localizedDescription ?? "Failed to authenticate")
                        }

                    }
                }
            } else {
                // no biometrics
                print(error?.localizedDescription ?? "Can't evaluate policy")

            }
        }
       } 

1 个答案:

答案 0 :(得分:1)

检查一下:

我不得不注释掉某些内容并更改某些内容,因为您的示例根本无法编译,但是如果您看到它,则应该对您清楚;)

echoCancellation: true