Face ID 登录

更新时间:2025-09-10 10:10:33下载pdf

功能概述

智能生活 iOS 版 App SDK 提供 Face ID 生物识别登录功能,基于系统的生物识别框架实现,支持 Face ID 的 iPhone 设备均可使用此功能,用户可以通过面容识别快速登录账号。

接入准备

  1. 首先,请确认项目已依赖最新版本的智能生活 App SDK。

  2. 导入所需框架:

    import ThingSmartLocalAuthKit
    
  3. 在项目的 Info.plist 中添加 Face ID 使用权限说明:

    <key>NSFaceIDUsageDescription</key>
    <string>App 需要您的同意才能使用 Face ID 进行登录</string>
    

ThingBiometricLoginManager 接口详解

检查设备硬件是否支持 Face ID 登录

接口说明

检查设备硬件是否支持 Face ID 登录功能。目前仅支持 Face ID。

- (BOOL)mobileHardwareSupportFaceIDLogin;

返回值

返回值 说明
YES 设备支持 Face ID 登录
NO 设备不支持 Face ID 登录

示例代码

Objc:

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")
}

检查生物识别登录是否已启用

接口说明

检查生物识别登录功能是否已启用。

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

参数说明

参数 说明
error 错误信息指针,如果检查失败会返回具体错误

返回值

返回值 说明
YES 生物识别登录已启用
NO 生物识别登录未启用

示例代码

Objc:

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)")
}

获取生物识别登录用户的账号信息

接口说明

获取已存储的生物识别登录用户的账号信息。

- (ThingBiometricLogiUserInfo *)getBiometricLoginUserAccountInfo;

返回值

返回值 说明
ThingBiometricLogiUserInfo 用户信息对象,包含:
  • userName:用户名
  • icon:头像 URL
  • uid:用户 ID
  • countryCode:国家代码
  • nickName:昵称

示例代码

Objc:

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")
}

更新当前账号生物识别登录信息

接口说明

更新已存储的用户显示名称和头像等生物识别登录信息。

- (void)updateCurrentAccountBiometricLoginInformation;

示例代码

Objc:

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

Swift:

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

开启生物识别登录

接口说明

开启生物识别登录功能,包括获取生物识别登录密钥和存储用户信息。

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

参数说明

参数 说明
policy 生物识别策略,通常为 .deviceOwnerAuthenticationWithBiometrics
localizedReason 认证请求的原因说明,会显示给用户
reply 完成回调,包含成功状态和错误信息

示例代码

Objc:

[biometricManager openBiometricLoginWithEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
      localizedReason:@"Enable Face ID login for your account"
                reply:^(BOOL success, NSError * _Nullable error) {
    if (success) {
        NSLog(@"Face ID enabled successfully");
        // 更新 UI 状态
        [self updateUIForEnabledFaceID];
    } else {
        NSLog(@"Failed to enable Face ID: %@", error.localizedDescription);
        // 显示错误信息
        [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")
        // 更新 UI 状态
        self.updateUIForEnabledFaceID()
    } else if let error = error {
        print("Failed to enable Face ID: \(error.localizedDescription)")
        // 显示错误信息
        self.showErrorAlert(error.localizedDescription)
    }
}

禁用生物识别登录

接口说明

禁用生物识别登录功能并清除已存储的生物识别数据。

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

参数说明

参数 说明
reply 完成回调,包含成功状态和错误信息

示例代码

Objc:

[biometricManager closeBiometricLogin:^(BOOL success, NSError * _Nullable error) {
    if (success) {
        NSLog(@"Face ID disabled successfully");
        // 更新 UI 状态
        [self updateUIForDisabledFaceID];
    } else {
        NSLog(@"Failed to disable Face ID: %@", error.localizedDescription);
        // 显示错误信息
        [self showErrorAlert:error.localizedDescription];
    }
}];

Swift:

biometricManager.closeBiometricLogin { success, error in
    if success {
        print("Face ID disabled successfully")
        // 更新 UI 状态
        self.updateUIForDisabledFaceID()
    } else if let error = error {
        print("Failed to disable Face ID: \(error.localizedDescription)")
        // 显示错误信息
        self.showErrorAlert(error.localizedDescription)
    }
}

生物识别登录

接口说明

使用生物识别认证进行登录,包括本地认证和服务器验证。

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

参数说明

参数 说明
policy 生物识别策略,通常为 .deviceOwnerAuthenticationWithBiometrics
localizedReason 认证请求的原因说明,会显示给用户
reply 完成回调,包含成功状态、结果数据和错误信息

示例代码

Objc:

[biometricManager loginByBiometricWithEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
       localizedReason:@"Login with Face ID"
                 reply:^(BOOL success, id result, NSError * _Nullable error) {
    if (success) {
        NSLog(@"Face ID login successful");
        // 处理登录成功
        [self handleSuccessfulLogin:result];
    } else {
        NSLog(@"Face ID login failed: %@", error.localizedDescription);
        // 处理登录失败
        [self handleFailedLogin:error];
    }
}];

Swift:

biometricManager.loginByBiometric(withEvaluatePolicy: .deviceOwnerAuthenticationWithBiometrics,
                                 localizedReason: "Login with Face ID") { success, result, error in
    if success {
        print("Face ID login successful")
        // 处理登录成功
        self.handleSuccessfulLogin(result)
    } else if let error = error {
        print("Face ID login failed: \(error.localizedDescription)")
        // 处理登录失败
        self.handleFailedLogin(error)
    }
}

错误码说明

ThingSmartLocalAuthError 错误码

错误码 说明
ThingSmartLocalAuthErrorBiometricLoginNotOpen (-5001) 生物识别登录未开启
ThingSmartLocalAuthErrorBiometricLoginInfoModified (-5002) 生物识别登录信息已修改

核心功能实现

初始化生物识别管理器

private let biometricManager = ThingBiometricLoginManager()

Face ID 状态检查

private func checkFaceIDStatus() -> Bool {
    // 检查设备是否支持 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
    }
    
    // 检查生物识别登录是否已启用
    do {
        let isEnabled = try biometricManager.isBiometricLoginEnabled()
        return isEnabled
    } catch {
        Alert.showBasicAlert(on: self, 
                           with: NSLocalizedString("FaceID Error", comment: ""), 
                           message: error.localizedDescription)
        return false
    }
}

启用 Face ID 登录

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)
            }
        }
    }
}

Face ID 登录实现

@IBAction func faceIDLoginTapped(_ sender: UIButton) {
    if self.checkFaceIDStatus() {
        // 执行 Face ID 认证登录
        biometricManager.loginByBiometric(withEvaluatePolicy: .deviceOwnerAuthenticationWithBiometrics,
                                         localizedReason: "Login with Face ID") { success, result, error in
            if success {
                // 登录成功,重置用户信息
                ThingSmartUser.sharedInstance().reset(userInfo: result as! [AnyHashable: Any], source: 9)
                
                // 跳转到主界面
                let storyboard = UIStoryboard(name: "ThingSmartMain", bundle: nil)
                let vc = storyboard.instantiateInitialViewController()
                self.window?.rootViewController = vc
            } else if let error = error {
                // 处理登录失败
                DispatchQueue.main.async {
                    Alert.showBasicAlert(on: self, 
                                       with: NSLocalizedString("FaceID Login Failed", comment: ""), 
                                       message: error.localizedDescription)
                }
            }
        }
    }
}

禁用 Face ID 登录

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)
            }
        }
    }
}

使用流程

  1. 用户通过普通账号密码方式完成登录。
  2. App 调用 openBiometricLoginWithEvaluatePolicy:localizedReason:reply: 开启 Face ID 功能,获取登录凭证,并自动保存 Face ID 相关数据。
  3. 用户后续再登录时,App 会直接调用 loginByBiometricWithEvaluatePolicy:localizedReason:reply: 来支持 Face ID 登录。

注意事项

  • 必须先调用 openBiometricLoginWithEvaluatePolicy:localizedReason:reply: 获取 Face ID 登录凭证,才能支持 Face ID 登录方式。
  • 当用户的 Face ID 信息发生变化时(如添加/删除面容),需要重新开启 Face ID 功能。
  • 如有以下情况,建议清除已存储的 Face ID 登录信息:
    • Face ID 信息变更。
    • 用户主动关闭 Face ID 登录功能。