Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LAContext canEvaluatePolicy and Swift 2

Tags:

ios

swift

swift2

This is my code in Swift:

if (LAContext().canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics)) {
  return true;
}

With Swift2 I changed my code to look like this:

if #available(iOS 8, *) {
            if (LAContext().canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics)) {
                return true;
            }
        }

But I get the following error:

Call can throw, but it is not marked with 'try' and the error is not handled

What Am I doing wrong?

like image 485
YogevSitton Avatar asked Mar 15 '23 14:03

YogevSitton


1 Answers

You need to do something like this:

do {
    try laContext.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics)

    // Call evaluatePolicy here
} catch {
    print("Cannot evaluate policy, error: \(error)")
}

All methods that returned a Bool and had an inout NSError? as the last parameter were automatically converted (Swift 2) to throw the error, so the parameter was removed. Also the Bool was redundant because it was equal to whether the inout NSError? is nil

EDIT: To get more information about the error use this within the catch:

switch LAError(rawValue: error.code)! {
case .AuthenticationFailed:
    break
case .UserCancel:
    break
case .UserFallback:
    break
case .SystemCancel:
    break
case .PasscodeNotSet:
    break
case .TouchIDNotEnrolled:
    break
default:
    break
}

(You can look at all the possible errors by CMD clicking on LAError

EDIT: In XCode 7 beta 5/6 this method doesn't throw anymore, but takes an NSErrorPointer as the last parameter (as does NSURL's checkResourceIsReachableAndReturnError for reasons not known to me). You can however extend your LAContext to make a throwing method like before if you like:

extension LAContext {
    func canEvaluatePolicyThrowing(policy: LAPolicy) throws {
        var error : NSError?
        canEvaluatePolicy(policy, error: &error)
        if let error = error { throw error }
    }
}
like image 168
Kametrixom Avatar answered Mar 25 '23 07:03

Kametrixom