You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Objective C中调用AppleScript实现密码提示支持Touch ID

问题解答

你当前使用的NSAppleScript调用do shell script搭配with administrator privileges参数的方案,底层依赖的是系统老旧的授权接口,本身原生不支持触发Touch ID验证,只会弹出密码输入框,无法仅通过修改AppleScript语法实现Touch ID支持。

如果要实现Touch ID验证能力,不需要完全抛弃现有AppleScript逻辑,可以搭配系统的生物验证框架实现,实现步骤如下:

  1. 先引入依赖框架:在项目中引入LocalAuthentication和Security两个系统框架,同时在头文件中导入对应头文件:
#import <LocalAuthentication/LocalAuthentication.h>
#import <Security/Security.h>
  1. 新增Touch ID前置校验逻辑,校验通过后再执行原有脚本:
LAContext *context = [[LAContext alloc] init];
NSError *biometricError = nil;

// 判断当前设备是否支持生物验证
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&biometricError]) {
    // 触发Touch ID验证
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
            localizedReason:@"需要管理员权限执行操作"
                      reply:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (success) {
                // Touch ID验证通过后,30s内调用原有AppleScript逻辑不会触发密码弹窗,用户感知等价于Touch ID授权
                NSDictionary *errorInfo = [NSDictionary new];
                NSString *script =  [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript];
                NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:script];
                [appleScript executeAndReturnError:&errorInfo];
            } else {
                // 验证失败可自行处理,比如fallback到原始密码授权逻辑
                NSLog(@"Touch ID验证失败:%@", error.localizedDescription);
            }
        });
    }];
} else {
    // 设备不支持Touch ID的情况,直接走原始逻辑
    NSDictionary *errorInfo = [NSDictionary new];
    NSString *script =  [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript];
    NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:script];
    [appleScript executeAndReturnError:&errorInfo];
}

注意事项

  • 需在项目的Info.plist中添加NSFaceIDUsageDescription字段,填写验证用途说明,否则生物验证会直接报错。
  • Touch ID通过后的授权窗口期默认是30秒,如果你要执行的脚本耗时较长,可以提前拆分授权和执行逻辑,避免窗口期失效后再次弹出密码框。

内容的提问来源于stack exchange,提问作者spartygw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 05:51:03