objective-c - Applescript 在脚本编辑器中有效,但在 Xcode 中无效
问题描述
我正在开发一个 mac 应用程序,它获取用户帐户的用户名和密码并切换到该用户帐户。
我有执行此操作的 AppleScript。当我从脚本编辑器运行它时,它工作正常。但是当我在 mac 应用程序中使用它时,相同的脚本不起作用。
切换到名为test的用户的 Apple 脚本:
set theUser to "test"
set thePassword to "test@123"
set theUser to do shell script "/usr/bin/id -u " & theUser
do shell script "/System/Library/CoreServices/'Menu Extras'/user.menu/Contents/Resources/CGSession -switchToUserID " & theUser
repeat 2 times
delay 2
try
tell application "System Events"
tell process "SecurityAgent"
set value of text field 1 of window "Login" to thePassword
key code 36
end tell
end tell
exit repeat
on error
delay 1
end try
end repeat
Mac 应用程序中使用的 Objective-C 代码:
NSAppleScript *switchUser = [[NSAppleScript alloc] initWithSource:
@"set theUser to \"test\" \n"
@"set thePassword to \"test@123\" \n"
@"set theUser to do shell script \"/usr/bin/id -u \" & theUser \n"
@"do shell script \"/System/Library/CoreServices/'Menu Extras'/user.menu/Contents/Resources/CGSession -switchToUserID \" & theUser \n"
@"repeat 2 times \n"
@" delay 1 \n"
@" try \n"
@" tell application \"System Events\" \n"
@" tell process \"SecurityAgent\" \n"
@" set value of text field 1 of window \"Login\" to thePassword \n"
@" key code 36 \n"
@" end tell \n"
@" end tell \n"
@" exit repeat \n"
@" on error \n"
@" delay 1 \n"
@" end try \n"
@"end repeat" ];
NSDictionary *err = nil;
[switchUser executeAndReturnError:&err];
if(err) {
NSLog(@"***** Apple script returned error: %@", err);
}
如果我在目标 C 中编写代码时遗漏了什么,请告诉我。或者是否有任何其他方式可以在用户之间切换。
解决方案
得到了问题。该脚本工作正常,但是当我们尝试切换用户时,当前用户的所有应用程序都会被杀死。这就是为什么它不起作用。
为了完成这项工作,我必须在守护程序服务中运行此脚本,该服务将运行而与用户帐户无关。
推荐阅读
- c# - 如何正确模拟调用不同项目中实现依赖注入的方法的控制器?
- node.js - 尝试在快速车把文件中呈现车把模板(未捕获的 ReferenceError:未定义车把)
- php - Codeigniter-检查用户是否存在于月份
- java - 未使用的变量警告
- grafana - 在普罗米修斯查询的右侧使用度量
- c++ - 类对象在 int main() 中为“未定义”
- keras - 功能 API/多输入模型超参数优化
- ruby-on-rails - 找到收入超过 10 年的公司
- javascript - 将厘米转换为英尺和英寸
- python - 使用 Jupyter notebook 在 Matplotlib 中执行 python 脚本文件,但它总是不显示数字。为什么?