如何向我的 Cocoa 应用程序添加 Applescript 支持?

发布于 2024-08-26 08:37:04 字数 110 浏览 3 评论 0原文

我是 Cocoa 编程领域的新手,我想向我的应用程序添加 Applescript 支持。苹果网站上的例子似乎已经过时了。

如何向我的 Cocoa 应用程序添加 Applescript 支持?

I am new to the world of Cocoa programming, and I want to add Applescript support to my application. The examples at Apple's website seem out of date.

How do I add Applescript support to my Cocoa application?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

与他有关 2024-09-02 08:37:04
  1. 如果您想从应用程序发送 AppleScript 并需要沙盒应用程序,则需要创建临时权利

  2. 您需要在 info.plist 中添加这两个密钥

    NSAppleScriptEnabled
    <真/>
    OSAScriptingDefinition
    <字符串>MyAppName.sdef
    

...当然您必须将“MyAppName”更改为您的应用程序名称

  1. 创建一个 .sdef 文件并将其添加到您的项目中。
    现在进一步的课程很大程度上取决于您的应用程序的需求,有:

    1. 类元素(从 AppleScript 创建对象)
    2. 命令元素(覆盖 NSScriptCommand 并执行“类似动词”的命令)
    3. 枚举元素
    4. 记录类型元素
    5. 值类型元素 (KVC)
    6. 可可元素

    -

    转到此处查找有关其实现的详细说明和许多细节:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_script_cmds/SAppsScriptCmds.html

  2. 我发现可以使用类和 KVC 元素非常复杂,因为我只想执行一个命令,没什么花哨的。因此,为了帮助其他人,这里有一个示例,说明如何使用一个参数创建一个新的简单命令。在此示例中,它将“查找”一个字符串,如下所示:

    告诉应用程序“MyAppName”
        查找“某个字符串”
    结束告诉
    
  3. 此命令的 .sdef 文件如下所示:

    
    
    
    <字典标题=“MyAppName”>
        <套件名称=“MyAppName Suite”代码=“MApN”描述=“MyAppName 脚本”>
            <命令名称=“lookup”代码=“lkpstrng”描述=“查找字​​符串,搜索条目”>
                <可可类=“MyLookupCommand”/>
                
                    <类型类型=“文本”/>
                
            
        
    
    
  4. 创建 NSScriptCommand 的子类并将其命名为 MyLookupCommand

    MyLookupCommand.h

    #import ;
    
    @interface MyLookupCommand : NSScriptCommand
    
    @结尾
    

    MyLookupCommand.m

    #import "MyLookupCommand.h"
    
    @实现MyLookupCommand
    
    -(id)performDefaultImplementation {
    
        // 获取参数
        NSDictionary *args = [自我评估参数];
        NSString *stringToSearch = @"";
        if(args.count) {
            stringToSearch = [args valueForKey:@""]; // 获取直接参数
        } 别的 {
            // 引发错误
            [自我设置脚本错误编号:-50];
            [self setScriptErrorString:@"参数错误:动词“查找”需要一个参数(您必须指定要查找的内容!)。"];
        }
        // 实现你的代码逻辑(在这个例子中,我只是发布一个内部通知)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AppShouldLookupStringNotification" 对象:stringToSearch];
        返回零;
    }
    
    @结尾
    

    基本上就是这样。其秘诀在于继承NSScriptCommand并覆盖performDefaultImplementation。我希望这可以帮助某人更快地获得它...

  1. If you want to send AppleScript from your application and need a sandboxed app, you need to create a temporary entitlement

  2. You need to add those two keys in your info.plist

    <key>NSAppleScriptEnabled</key>
    <true/>
    <key>OSAScriptingDefinition</key>
    <string>MyAppName.sdef</string>
    

...of course you have to change "MyAppName" to your app's name

  1. Create a .sdef file and add it to your project.
    The further course now greatly depends on the needs of your application, there are:

    1. Class Elements (create an object from AppleScript)
    2. Command Elements (override NSScriptCommand and execute "verb-like" commands)
    3. Enumeration Elements
    4. Record-Type Elements
    5. Value-Type Elements (KVC)
    6. Cocoa Elements

    -

    Go here to find a detailed description and many details on their implementation: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_script_cmds/SAppsScriptCmds.html

  2. I found working with Class and KVC Elements very complicated, as I just wanted to execute a single command, nothing fancy. So in order to help others, here's an example of how to create a new simple command with one argument. In this example it'll "lookup" one string like this:

    tell application "MyAppName"
        lookup "some string"
    end tell
    
  3. The .sdef file for this command looks like this:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">
    
    <dictionary title="MyAppName">
        <suite name="MyAppName Suite" code="MApN" description="MyAppName Scripts">
            <command name="lookup" code="lkpstrng" description="Look up a string, searches for an entry">
                <cocoa class="MyLookupCommand"/>
                <direct-parameter description="The string to lookup">
                    <type type="text"/>
                </direct-parameter>
            </command>
        </suite>
    </dictionary>
    
  4. Create a subclass of NSScriptCommand and name it MyLookupCommand

    The MyLookupCommand.h

    #import <Foundation/Foundation.h>
    
    @interface MyLookupCommand : NSScriptCommand
    
    @end
    

    The MyLookupCommand.m

    #import "MyLookupCommand.h"
    
    @implementation MyLookupCommand
    
    -(id)performDefaultImplementation {
    
        // get the arguments
        NSDictionary *args = [self evaluatedArguments];
        NSString *stringToSearch = @"";
        if(args.count) {
            stringToSearch = [args valueForKey:@""];    // get the direct argument
        } else {
            // raise error
            [self setScriptErrorNumber:-50];
            [self setScriptErrorString:@"Parameter Error: A Parameter is expected for the verb 'lookup' (You have to specify _what_ you want to lookup!)."];
        }
        // Implement your code logic (in this example, I'm just posting an internal notification)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AppShouldLookupStringNotification" object:stringToSearch];
        return nil;
    }
    
    @end
    

    That's basically it. The secret to this is to subclass NSScriptCommand and override performDefaultImplementation. I hope this helps someone to get it faster...

二智少女猫性小仙女 2024-09-02 08:37:04

现代版本的 Cocoa 可以直接解释脚本定义 (.sdef) 属性列表,因此对于基本 AppleScript 支持,您所需要做的就是根据文档创建 sdef,将其添加到“复制捆绑资源”阶段并声明 AppleScript 支持在你的 Info.plist 中。要访问 NSApp 以外的对象,您需要定义对象说明符,以便每个对象都知道其在脚本世界层次结构中的位置。这使您能够对对象属性进行 kvc 操作,并能够将对象方法用作简单的脚本命令。

Modern versions of Cocoa can directly interpret the scripting definition (.sdef) property list, so all you need to do for basic AppleScript support is to create the sdef per the docs, add it to your "copy bundle resources" phase and declare AppleScript support in your Info.plist. To access objects other than NSApp, you define object specifiers, so each object knows its position in the scripting world's hierarchy. That gets you kvc manipulation of object properties, and the ability to use object methods as simple script commands.

无妨# 2024-09-02 08:37:04

一个简单的例子可以帮助您入门,

将一个脚本(名为对话框)放入文档文件夹中,然后您可以从 Xcode 运行它。

NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [arrayPaths objectAtIndex:0];
    NSString *filePath = [docDirectory stringByAppendingString:@"/dialog.scpt"];

     NSAppleScript *scriptObject = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];

 [scriptObject executeAndReturnError:nil];

将脚本保留在外部的好处是能够在 Xcode 之外对其进行编辑。
如果您确实开始编辑,我建议添加错误检查,因为 applescript 可能无法编译,

也许可以检查

if(scriptObject.isCompiled){

A simple example to get you started,

place a script (named dialog) into the documents folder then you can run it from Xcode

NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [arrayPaths objectAtIndex:0];
    NSString *filePath = [docDirectory stringByAppendingString:@"/dialog.scpt"];

     NSAppleScript *scriptObject = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:nil];

 [scriptObject executeAndReturnError:nil];

The nice thing about keeping the script external is the ability to edit it outside of Xcode.
I would recommend adding the error checking if you did start editing as the applescript may not compile

maybe check with

if(scriptObject.isCompiled){
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文