Face ID Login

Last Updated on : 2025-09-10 06:26:22download

Overview

SmartLife App SDK for iOS provides biometric login via Face ID, implemented based on the system’s biometric authentication framework. This feature is available on all iPhone devices supporting Face ID, allowing users to quickly log in to their accounts using facial recognition.

Preparations

  1. First, make sure your project depends on the latest version of the SmartLife App SDK.

  2. Import the required framework.

    import ThingSmartLocalAuthKit
    
  3. Add the Face ID usage description to your project’s Info.plist.

    <key>NSFaceIDUsageDescription</key>
    <string>The app requires your consent to log in using Face ID.</string>
    

ThingBiometricLoginManager description

Check support for Face ID login

API description

Check whether the device hardware supports Face ID login functionality. Currently, only Face ID is supported.

- (BOOL)mobileHardwareSupportFaceIDLogin;

Return value

Return value Description
YES The device supports Face ID login.
NO The device does not support Face ID login.

Example

Objective-C:

BOOL isSupported = [biometricManager mobileHardwareSupportFaceIDLogin];
if (isSupported) {
    NSLog(@"Device supports Face ID login");
} else {
    NSLog(@"Device does not support Face ID login");
}

Swift:

let isSupported = biometricManager.mobileHardwareSupportFaceIDLogin()
if isSupported {
    print("Device supports Face ID login")
} else {
    print("Device does not support Face ID login")
}

Check if biometric login is enabled

API description

Check if the biometric login functionality is enabled.

- (BOOL)isBiometricLoginEnabled:(NSError * __autoreleasing *)error;

Parameter description

Parameter Description
error The pointer to error information. Specific error details are returned if the check fails.

Return value

Return value Description
YES The biometric login functionality is enabled.
NO The biometric login functionality is not enabled.

Example

Objective-C:

NSError *error = nil;
BOOL isEnabled = [biometricManager isBiometricLoginEnabled:&error];
if (isEnabled) {
    NSLog(@"Biometric login is enabled");
} else {
    NSLog(@"Biometric login is not enabled: %@", error.localizedDescription);
}

Swift:

do {
    let isEnabled = try biometricManager.isBiometricLoginEnabled()
    if isEnabled {
        print("Biometric login is enabled")
    } else {
        print("Biometric login is not enabled")
    }
} catch {
    print("Error checking biometric login status: \(error.localizedDescription)")
}

Get user account

API description

Get the stored account information of the user registered for biometric login.

- (ThingBiometricLogiUserInfo *)getBiometricLoginUserAccountInfo;

Return value

Return value Description
ThingBiometricLogiUserInfo The user information object, including:
  • userName: username
  • icon: avatar URL
  • uid: user ID
  • countryCode: country code
  • nickName: nickname

Example

Objective-C:

ThingBiometricLogiUserInfo *userInfo = [biometricManager getBiometricLoginUserAccountInfo];
if (userInfo) {
    NSLog(@"User ID: %@", userInfo.uid);
    NSLog(@"Username: %@", userInfo.userName);
    NSLog(@"Nickname: %@", userInfo.nickName);
    NSLog(@"Icon: %@", userInfo.icon);
    NSLog(@"Country Code: %@", userInfo.countryCode);
} else {
    NSLog(@"No biometric login user info found");
}

Swift:

if let userInfo = biometricManager.getBiometricLoginUserAccountInfo() {
    print("User ID: \(userInfo.uid ?? "")")
    print("Username: \(userInfo.userName ?? "")")
    print("Nickname: \(userInfo.nickName ?? "")")
    print("Icon: \(userInfo.icon ?? "")")
    print("Country Code: \(userInfo.countryCode ?? "")")
} else {
    print("No biometric login user info found")
}

Update biometric login information

API description

Update the stored biometric login information, including the user’s display name and avatar.

- (void)updateCurrentAccountBiometricLoginInformation;

Example

Objective-C:

[biometricManager updateCurrentAccountBiometricLoginInformation];
NSLog(@"Biometric login information updated");

Swift:

biometricManager.updateCurrentAccountBiometricLoginInformation()
print("Biometric login information updated")

Enable biometric login

API description

Enable biometric login functionality, including obtaining biometric login keys and storing user information.

- (void)openBiometricLoginWithEvaluatePolicy:(LAPolicy)policy
      localizedReason:(NSString *)localizedReason
                reply:(void(^)(BOOL success,NSError * __nullable error))reply;

Parameter description

Parameter Description
policy The biometric authentication policy, typically .deviceOwnerAuthenticationWithBiometrics.
localizedReason The explanation for the authentication request displayed to the user.
reply The completion callback, including success status and error information.

Example

Objective-C:

[biometricManager openBiometricLoginWithEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
      localizedReason:@"Enable Face ID login for your account"
                reply:^(BOOL success, NSError * _Nullable error) {
    if (success) {
        NSLog(@"Face ID enabled successfully");
        // Update UI state
        [self updateUIForEnabledFaceID];
    } else {
        NSLog(@"Failed to enable Face ID: %@", error.localizedDescription);
        // Show an error
        [self showErrorAlert:error.localizedDescription];
    }
}];

Swift:

biometricManager.openBiometricLogin(withEvaluatePolicy: .deviceOwnerAuthenticationWithBiometrics,
                                   localizedReason: "Enable Face ID login for your account") { success, error in
    if success {
        print("Face ID enabled successfully")
        // Update UI state
        self.updateUIForEnabledFaceID()
    } else if let error = error {
        print("Failed to enable Face ID: \(error.localizedDescription)")
        // Show an error
        self.showErrorAlert(error.localizedDescription)
    }
}

Disable biometric login

API description

Disable biometric login and clear the stored biometric data.

- (void)closeBiometricLogin:(void(^)(BOOL success, NSError * __nullable error))reply;

Parameter description

Parameter Description
reply The completion callback, including success status and error information.

Example

Objective-C:

[biometricManager closeBiometricLogin:^(BOOL success, NSError * _Nullable error) {
    if (success) {
        NSLog(@"Face ID disabled successfully");
        // Update UI state
        [self updateUIForDisabledFaceID];
    } else {
        NSLog(@"Failed to disable Face ID: %@", error.localizedDescription);
        // Show an error
        [self showErrorAlert:error.localizedDescription];
    }
}];

Swift:

biometricManager.closeBiometricLogin { success, error in
    if success {
        print("Face ID disabled successfully")
        // Update UI state
        self.updateUIForDisabledFaceID()
    } else if let error = error {
        print("Failed to disable Face ID: \(error.localizedDescription)")
        // Show an error
        self.showErrorAlert(error.localizedDescription)
    }
}

Perform biometric login

API description

Perform login using biometric authentication, including local authentication and server verification.

- (void)loginByBiometricWithEvaluatePolicy:(LAPolicy)policy
       localizedReason:(NSString *)localizedReason
                 reply:(void(^)(BOOL success, id result, NSError * __nullable error))reply;

Parameter description

Parameter Description
policy The biometric authentication policy, typically .deviceOwnerAuthenticationWithBiometrics.
localizedReason The explanation for the authentication request displayed to the user.
reply The completion callback, including success status, result data, and error information.

Example

Objective-C:

[biometricManager loginByBiometricWithEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
       localizedReason:@"Login with Face ID"
                 reply:^(BOOL success, id result, NSError * _Nullable error) {
    if (success) {
        NSLog(@"Face ID login successful");
        // Handled login successfully
        [self handleSuccessfulLogin:result];
    } else {
        NSLog(@"Face ID login failed: %@", error.localizedDescription);
        // Failed to handle login
        [self handleFailedLogin:error];
    }
}];

Swift:

biometricManager.loginByBiometric(withEvaluatePolicy: .deviceOwnerAuthenticationWithBiometrics,
                                 localizedReason: "Login with Face ID") { success, result, error in
    if success {
        print("Face ID login successful")
        // Handled login successfully
        self.handleSuccessfulLogin(result)
    } else if let error = error {
        print("Face ID login failed: \(error.localizedDescription)")
        // Failed to handle login
        self.handleFailedLogin(error)
    }
}

Error codes

ThingSmartLocalAuthError error codes

No. Description
ThingSmartLocalAuthErrorBiometricLoginNotOpen (-5001) The biometric login functionality is not enabled.
ThingSmartLocalAuthErrorBiometricLoginInfoModified (-5002) The biometric login information has been modified.

Implement core features

Initialize biometric manager

private let biometricManager = ThingBiometricLoginManager()

Check Face ID status

private func checkFaceIDStatus() -> Bool {
    // Check support for Face ID
    guard biometricManager.mobileHardwareSupportFaceIDLogin() else {
        Alert.showBasicAlert(on: self,
                           with: NSLocalizedString("FaceID Not Available", comment: ""),
                           message: "Device does not support Face ID")
        return false
    }

    // Check if biometric login is enabled
    do {
        let isEnabled = try biometricManager.isBiometricLoginEnabled()
        return isEnabled
    } catch {
        Alert.showBasicAlert(on: self,
                           with: NSLocalizedString("FaceID Error", comment: ""),
                           message: error.localizedDescription)
        return false
    }
}

Enable Face ID login

private func openBiometricLogin() {
    biometricManager.openBiometricLogin(withEvaluatePolicy: .deviceOwnerAuthenticationWithBiometrics,
                                       localizedReason: "Enable Face ID login") { success, error in
        DispatchQueue.main.async {
            if success {
                self.syncButton.setTitle("Synchronized", for: .normal)
            } else if let error = error {
                Alert.showBasicAlert(on: self,
                                   with: NSLocalizedString("FaceID Error", comment: ""),
                                   message: error.localizedDescription)
            }
        }
    }
}

Perform Face ID login

@IBAction func faceIDLoginTapped(_ sender: UIButton) {
    if self.checkFaceIDStatus() {
        // Execute Login via Face ID authentication
        biometricManager.loginByBiometric(withEvaluatePolicy: .deviceOwnerAuthenticationWithBiometrics,
                                         localizedReason: "Login with Face ID") { success, result, error in
            if success {
                // Login was successful. Reset user information
                ThingSmartUser.sharedInstance().reset(userInfo: result as! [AnyHashable: Any], source: 9)

                // Go to the main interface
                let storyboard = UIStoryboard(name: "ThingSmartMain", bundle: nil)
                let vc = storyboard.instantiateInitialViewController()
                self.window?.rootViewController = vc
            } else if let error = error {
                // Failed to handle login
                DispatchQueue.main.async {
                    Alert.showBasicAlert(on: self,
                                       with: NSLocalizedString("FaceID Login Failed", comment: ""),
                                       message: error.localizedDescription)
                }
            }
        }
    }
}

Disable Face ID login

private func closeBiometricLogin() {
    biometricManager.closeBiometricLogin { success, error in
        DispatchQueue.main.async {
            if success {
                self.syncButton.setTitle("Not synchronized", for: .normal)
            } else if let error = error {
                Alert.showBasicAlert(on: self,
                                   with: NSLocalizedString("FaceID Error", comment: ""),
                                   message: error.localizedDescription)
            }
        }
    }
}

Procedure

  1. A user completes login through the standard account and password method.
  2. The app invokes openBiometricLoginWithEvaluatePolicy:localizedReason:reply: to enable Face ID functionality, get login credentials, and automatically save Face ID-related data.
  3. When the user logs in again later, the app directly invokes loginByBiometricWithEvaluatePolicy:localizedReason:reply: to support Face ID login.

Considerations

  • The openBiometricLoginWithEvaluatePolicy:localizedReason:reply: method must be invoked first to get Face ID login credentials. And then, Face ID login can be supported.
  • When a user’s Face ID information changes, such as adding or removing a face, the Face ID feature must be re-enabled.
  • It is recommended to clear the stored Face ID login information in the following cases:
    • The Face ID information is modified.
    • The user proactively disables the Face ID login functionality.