Local Authentication: Swift 4.2
Hello Everyone, This article will be going to teach about Local Authentication. How to use, implement with using a custom struct. Hope you will like it.
A quick demonstrate regarding what we going to learn in this tutorial.
As you can see, a single authenticate button when I pressed, it presents Authentication alert which allows us to scan our biometric with reason message why we want to use user biometric. If user authentication is successfully completed then I have shown an alert popup with a successfully authenticated message. If the user biometric unable to recognize, so we can use passcode fallback functionality for the authentication.
I'm assuming that you are familiar with project setup. Open Storyboard, Drag an UIButton named it as Authenticate. Jump to ViewController Class create an IBOutlet for Authenticate button and IBAction for it. That's it for design related stuff.
Create a new swift file and named it properly, mine is LocalAuthentication. In this file, we are going to create a class as per the naming of the swift file. Now we need to create some couples variable because we will be going to use them later. The first variable we going declare is for checking the availability of FaceID "isFaceIdAvailable" which will return true or false.
Here in this static variable, we declare an object of LAContext. Here LA stands for Local Authentication. LAContext is used for evaluating LAPolicy which will be going to help with checking the availability of FaceID. After that, creating a variable which can evaluate policy using device owner authentication with biometrics and error as nil. Thus return evaluate object alone with context biometric type equal to FaceID. If you want a variable for checking "isTouchIdAvailable", just change context biometric type to TouchID.
We required a reason message why we want to use FaceID or TouchID. So I'm going to create a file-private default reason message variable which will be going to return String using ternary condition. If FaceID is available return "kFaceIdAuthenticationReason" or else return TouchID message "kTouchIdAuthenticationReason". Please, check constants swift file for messages I have created to save some time.
Authentication has a different state like success, failed, cancel and many other. So I have created an enumeration for it which going to help us with the authentication state type, also declare a function for state message which will return message as per state. Please check the Authentication Block State file for more detail.
Thus creating type alias authentication block declaration which will help us for stating the state of authentication type.
Hope you are getting. I'm simplifying as possible.
Lastly, we going to create a function authenticate a user with biometrics with the following parameters:
In this function, we have declared a variable of LAContext which provide a user interface of authentication, using this variable we can able to pass localized cancel title and also fall back title which I will be going to pass static String "Passcode".
If you wondering about what is fall back?. Fall back is an option where user biometrics attempt gets failed and provide an interface of passcode entering by pressing Passcode Fallback.
At last, evaluate policy using device owner authentication. Here LAPolicy is an enumeration has two type device owner authentication with biometrics and device owner authentication.
What's different right? As per my understanding, device owner authentication with biometrics will be going to work only if the user has enabled biometric on the device and for the device owner authentication
works for both passcode and biometric too. So I always prefer device owner authentication.
Respective reason message of it and reply block contains two parameters Boolean and Optional Error, hit an enter initialized our custom block with down casting Error to LAError.
Now we just need to implement this method in IBAction of Authenticate button, with passing following reason why we want to use user biometric and block will return the state of authentication. Thus we can able to handle authentication state using switch struct.
Just run an application on a device you are good to go.Thanks for staying at the end, I really appreciate. Please like, share and feel free to comment for any query. Full Code.
Hello Everyone, This article will be going to teach about Local Authentication. How to use, implement with using a custom struct. Hope you will like it.
A quick demonstrate regarding what we going to learn in this tutorial.
As you can see, a single authenticate button when I pressed, it presents Authentication alert which allows us to scan our biometric with reason message why we want to use user biometric. If user authentication is successfully completed then I have shown an alert popup with a successfully authenticated message. If the user biometric unable to recognize, so we can use passcode fallback functionality for the authentication.
I'm assuming that you are familiar with project setup. Open Storyboard, Drag an UIButton named it as Authenticate. Jump to ViewController Class create an IBOutlet for Authenticate button and IBAction for it. That's it for design related stuff.
Create a new swift file and named it properly, mine is LocalAuthentication. In this file, we are going to create a class as per the naming of the swift file. Now we need to create some couples variable because we will be going to use them later. The first variable we going declare is for checking the availability of FaceID "isFaceIdAvailable" which will return true or false.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Variable Declaration(s) | |
class var isFaceIdAvailable: Bool { | |
let context: LAContext = LAContext() | |
let evaluate = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) | |
if #available(iOS 11.0, *) { | |
return (context.biometryType == .faceID) | |
} | |
return evaluate | |
} |
We required a reason message why we want to use FaceID or TouchID. So I'm going to create a file-private default reason message variable which will be going to return String using ternary condition. If FaceID is available return "kFaceIdAuthenticationReason" or else return TouchID message "kTouchIdAuthenticationReason". Please, check constants swift file for messages I have created to save some time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Change default message as per your need. | |
fileprivate static var defaultReasonMessage: String { | |
return LocalAuthentication.isFaceIdAvailable ? kFaceIdAuthenticationReason : kTouchIdAuthenticationReason | |
} |
Thus creating type alias authentication block declaration which will help us for stating the state of authentication type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Block Declaration(s) | |
typealias authenticationBlock = ((AuthenticationBlockState) -> ()) |
Lastly, we going to create a function authenticate a user with biometrics with the following parameters:
- Reason message: Here message cannot be nil, we need to provide a reason for using user biometrics
- Cancel Title: This can be optional.
- Block: This will be going to return a state of authentication.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class func authenticateUserWithBioMetrics(_ reasonMessage: String, cancelTitle: String? = "", block: @escaping authenticationBlock) { | |
let context: LAContext = LAContext() | |
context.localizedCancelTitle = cancelTitle | |
context.localizedFallbackTitle = "Passcode" | |
evaluate(.deviceOwnerAuthentication, reason: (reasonMessage.isEmpty ? defaultReasonMessage : reasonMessage), context: context, block: block) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fileprivate static func evaluate(_ policy: LAPolicy, reason: String, context: LAContext, block: @escaping authenticationBlock) { | |
context.evaluatePolicy(policy, localizedReason: reason) { (isSuccess, error) in | |
block(AuthenticationBlockState.initWith(error as? LAError)) | |
} | |
} |
If you wondering about what is fall back?. Fall back is an option where user biometrics attempt gets failed and provide an interface of passcode entering by pressing Passcode Fallback.
At last, evaluate policy using device owner authentication. Here LAPolicy is an enumeration has two type device owner authentication with biometrics and device owner authentication.
What's different right? As per my understanding, device owner authentication with biometrics will be going to work only if the user has enabled biometric on the device and for the device owner authentication
works for both passcode and biometric too. So I always prefer device owner authentication.
Respective reason message of it and reply block contains two parameters Boolean and Optional Error, hit an enter initialized our custom block with down casting Error to LAError.
Now we just need to implement this method in IBAction of Authenticate button, with passing following reason why we want to use user biometric and block will return the state of authentication. Thus we can able to handle authentication state using switch struct.
This is a wonderful blog post. Thanks for sharing information on Swift App Development Company. For more details kindly visit us at Swift App Development Company in India. Call us: +91-7314236251 or mail us at sales@samosys.com
ReplyDeleteVery Helpful Information!
ReplyDeleteNKU Technologies
Mobile Application Development
Web Application Development
Business Application Development