LAContext可以评估策略和Swift 2 [英] LAContext canEvaluatePolicy and Swift 2
问题描述
这是我在Swift中的代码:
This is my code in Swift:
if (LAContext().canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics)) {
return true;
}
使用Swift2我将代码更改为:
With Swift2 I changed my code to look like this:
if #available(iOS 8, *) {
if (LAContext().canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics)) {
return true;
}
}
但是我收到以下错误:
调用可以抛出,但没有标记'try'并且没有处理错误
Call can throw, but it is not marked with 'try' and the error is not handled
我做错了什么?
推荐答案
你需要这样做:
do {
try laContext.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics)
// Call evaluatePolicy here
} catch {
print("Cannot evaluate policy, error: \(error)")
}
所有返回 Bool
并且 inout NSError?
的方法为最后一个参数被自动转换(Swift 2)以抛出错误,因此删除了参数。另外 Bool
是多余的,因为它等于 inout NSError?
是否为零
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
编辑:要获得有关错误的更多信息,请在catch中使用:
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
}
(您可以通过CMD点击 LAError
(You can look at all the possible errors by CMD clicking on LAError
编辑:在XCode 7 beta 5/6中,此方法不再抛出,但需要 NSErrorPointer
作为最后一个参数(因为 NSURL
的 checkResourceIsReachableAndReturnError
,因为我不知道的原因)。但是你可以扩展你的 LAContext
如果您愿意,可以像以前一样制作投掷方法:
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 }
}
}
这篇关于LAContext可以评估策略和Swift 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!