2016-05-06 72 views
0

我想基於觸摸ID的成功/失敗返回true或false。但是,如果條件被調用,那麼成功的時候,該函數會以一個錯誤的值退出。我是iOS開發新手。我相信我應該使用某種完成處理程序,但在這個特定情況下,我不明白如何處理。成功觸摸ID設置變量

func authenticateUser(reasonString: String) -> Bool { 
    // Get the local authentication context. 
    let context = LAContext() 

    // Declare a NSError variable. 
    var error: NSError? 

    // Current authorization status of user 
    var isAuthorized = false 

    // Check if the device can evaluate the policy. 
    if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) { 
     [context .evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success: Bool, evalPolicyError: NSError?) -> Void in 

      if success { 
       isAuthorized = true 
      } 
      else{ 
       // If authentication failed then show a message to the console with a short description. 
       // In case that the error is a user fallback, then show the password alert view. 
       print(evalPolicyError?.localizedDescription) 

       switch evalPolicyError!.code { 

       case LAError.SystemCancel.rawValue: 
        print("Authentication was cancelled by the system") 

       case LAError.UserCancel.rawValue: 
        print("Authentication was cancelled by the user") 

       case LAError.UserFallback.rawValue: 
        print("User selected to enter custom password") 

       default: 
        print("Authentication failed") 

       } 
      } 

     })] 
    } 
    else{ 
     // If the security policy cannot be evaluated then show a short message depending on the error. 
     switch error!.code{ 

     case LAError.TouchIDNotEnrolled.rawValue: 
      print("TouchID is not enrolled") 

     case LAError.PasscodeNotSet.rawValue: 
      print("A passcode has not been set") 

     default: 
      // The LAError.TouchIDNotAvailable case. 
      print("TouchID not available") 
     } 

     // Optionally the error description can be displayed on the console. 
     print(error?.localizedDescription) 

    } 
return isAuthorized 
} 

即使在執行touchID部件之前,此函數也會返回false。有人可以指導嗎?

回答

0

您的函數authenticateUser將始終返回false,因爲您返回的是isAuthority值,該值設置爲false。 context.canEvaluatePolicy和context.evaluatePolicy仍在執行,值不會更改爲isAuthorized。

實際流量是有點像這樣:

集isAuthorized ==假

{調用context.canEvaluatePolicy - >仍在執行 呼叫context.evaluatePolicy - 對context.canEvaluatePolicy的成功>}

返回isAuthorized = False - > context.canEvaluatePolicy和context.evaluatePolicy仍在執行。

即使Block Methods正在執行,執行流程完成方法的執行。

我的建議是從函數的最後去掉return isAuthorized並實現成功和失敗塊。