【问题标题】:Applescript works in Script Editor but not in XcodeApplescript 在脚本编辑器中有效,但在 Xcode 中无效
【发布时间】:2020-11-27 22:03:11
【问题描述】:

我正在开发一个mac应用程序,它获取用户帐户的用户名和密码并切换到该用户帐户。

我有执行此操作的 AppleScript。当我从脚本编辑器运行它时,它工作正常。但是当我在 mac 应用程序中使用它时,相同的脚本不起作用。

Apple 脚本切换到名为 test 的用户:

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 中编写代码时遗漏了什么,请告诉我。或者是否有任何其他方式可以在用户之间切换。

【问题讨论】:

  • 至少不要忽略可能的错误。传递一个NSDictionary 指针并查看它包含的内容。应用程序是否被沙盒化?如果是,您将无法使用 NSAppleScript 运行脚本
  • 应用没有沙盒化。

标签: objective-c applescript


【解决方案1】:

有问题。该脚本工作正常,但是当我们尝试切换用户时,当前用户的所有应用程序都会被杀死。这就是它不起作用的原因。

为了完成这项工作,我必须在守护程序服务中运行此脚本,该服务将运行而与用户帐户无关。

【讨论】:

    猜你喜欢
    • 2014-07-22
    • 2015-11-04
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 2018-05-29
    • 1970-01-01
    相关资源
    最近更新 更多