macos - 通过 NSAppleScript 发送击键时出现错误 1002
问题描述
我想将击键发送到 OBS 以触发场景更改。我已经编写了一个通过 AppleScript 执行此操作的方法:
+ (void)sendKeyWithControlDown:(NSString*)key afterMSDelay:(NSInteger)delay toOBSType:(OBSType)obsType completion:(void(^)(NSDictionary *error))completion {
NSString *appName = (obsType == OBSTypeOBS) ? @"OBS" : @"RPAN Studio";
NSString *source = [NSString stringWithFormat:@"tell application \"%@\" to activate \n tell application \"System Events\" to keystroke \"%@\" using control down", appName, key];
NSAppleScript *applescript = [[NSAppleScript alloc] initWithSource:source];
NSDictionary *dict;
[applescript executeAndReturnError:&dict];
completion(dict);
}
字典返回错误 1002,说System Events got an error: <my app> is not allowed to send keystrokes
我尝试了以下方法:
- 禁用应用程序沙箱(此软件仅供我使用)
- 添加
com.apple.security.temporary-exception.apple-events
和Apple Events
到权利文件,每个都有一个真值 - 使用描述添加
Privacy - AppleEvents Sending Usage Description
到应用程序的 info.plist。该应用程序会在我第一次运行新版本时询问我是否允许这样做,我同意,并且该应用程序System Preferences > Security & Privacy
同时显示在Accessibility
和Automation
部分中。它在两个位置都打勾。我试过取消勾选和重新勾选 - 清洁和重建
- 删除派生数据
它已经工作了几次,但还不足以找出它停止的原因。在它工作和停止工作之间,我没有进行任何代码更改。
解决方案
似乎取消并重新勾选了系统偏好设置中的权限,我忘记了您实际上可以将它们从列表中删除。我认为它已经存储了不同构建的权限,并且对我允许的应用程序感到困惑。删除并重新添加后,它起作用了。