1

我正在尝试让 TouchID 对我的应用程序上的操作进行身份验证。如果成功,我需要它来显示 ImageView。

这是我在 ViewController 中的代码

@IBOutlet weak var notificationImage: UIImageView!
@IBAction func touchBtn(_ sender: UIButton) {    
    context = LAContext()
    var error: NSError?
    if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
        let reason = "Authenticate"
        context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason ) { success, error in
             if success {
                 print("In closure")
                 // Move to the main thread because a state update triggers UI changes.
                 DispatchQueue.main.async{
                     print("In main thread: Success")
                     self.notificationImage.isHidden = false
                  }
              } else {
                  DispatchQueue.main.async(execute: {
                      print("In main thread: Failed")
                  })
              }    
          }
      }
}

我能够使用 TouchID 成功进行身份验证。它打印“关闭中”。但是 DispatchQueue.main.async 中的块没有执行,我无法更新 notificationImage:UIImageView。它也不会在 sync{} 块中打印任何内容。

我试图禁用主线程检查器并删除 DispatchQueue.main.async 部分,但视图有时会刷新,有时不会。我想使用推荐的做法并从主线程更新 UI。

我在 Xcode 9 Swift 4 iOS 11.4

这里可能有什么问题。

4

1 回答 1

0

试试这个代码

  @IBAction func touchBtn(_ sender: UIButton) {
   let context = LAContext()
    var error: NSError?
    if context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) {
        let reason = "Authenticate"
        context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason ) { success, error in
            if success {
                do {
                    print("In closure")
                    print("In main thread: Success")
                    self.notificationImage.isHidden = false

                } catch let error as NSError {
                    print(error.localizedDescription)
                    print(error.description)
                }

            } else {
                DispatchQueue.main.async(execute: {
                    print("In main thread: Failed")
                })
            }
        }
    }
}
于 2018-06-27T10:08:46.220 回答