【问题标题】:Run AppleScript from Cocoa Application从 Cocoa 应用程序运行 AppleScript
【发布时间】:2011-02-05 21:15:01
【问题描述】:

是否可以在 Cocoa 应用程序中运行 AppleScript 代码?

我尝试过 NSAppleScript 类,但没有成功。

另外,Apple 允许这样做吗?

【问题讨论】:

  • NSAppleScript 是一个公共类,因此 Apple 的 App Store 指南允许。

标签: objective-c cocoa applescript


【解决方案1】:

解决了!

Xcode 没有将我的脚本文件保存到应用的资源路径中。要从 Cocoa 应用程序运行 AppleScript 代码,请使用:

NSString* path = [[NSBundle mainBundle] pathForResource:@"ScriptName" ofType:@"scpt"];
NSURL* url = [NSURL fileURLWithPath:path];NSDictionary* errors = [NSDictionary dictionary];
NSAppleScript* appleScript = [[NSAppleScript alloc] initWithContentsOfURL:url error:&errors];
[appleScript executeAndReturnError:nil];
[appleScript release];

【讨论】:

  • 我有苹果脚本,我可以从中获取邮件正文和主题。当我从上面的代码调用这个脚本时,我怎样才能得到这个邮件的结果数据(邮件正文和主题)?
【解决方案2】:

您提到 xcode 没有将脚本保存到您应用的资源路径中。那是对的。你必须告诉 xcode 这样做。首先将编译好的脚本添加到您的项目中。然后打开您的目标并找到“复制捆绑资源”操作。将您的脚本从文件列表拖到该操作中。通过这种方式,您的脚本会自动复制到您应用的资源中,因此您无需手动操作。

每当我在可可应用程序中使用已编译的 AppleScript 时,我,1) 将脚本添加到项目中,2) 创建一个新类来控制 AppleScript,3) 对该类使用下面的 init 方法,以及 4) 拖动将脚本复制到目标的“复制捆绑资源”操作中。

- (id)init {
    NSURL *scriptURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:@"applescripts" ofType:@"scpt"]];
    if ([self initWithURLToCompiledScript:scriptURL] != nil) { //attempt to load the script file
    }

    return self;
}

【讨论】:

    【解决方案3】:

    来自 Apple 文档 https://developer.apple.com/library/mac/technotes/tn2084/_index.html

    - (IBAction)addLoginItem:(id)sender
    {
        NSDictionary* errorDict;
        NSAppleEventDescriptor* returnDescriptor = NULL;
    
        NSAppleScript* scriptObject = [[NSAppleScript alloc] initWithSource:
                    @"\
                    set app_path to path to me\n\
                    tell application \"System Events\"\n\
                    if \"AddLoginItem\" is not in (name of every login item) then\n\
                    make login item at end with properties {hidden:false, path:app_path}\n\
                    end if\n\
                    end tell"];
    
        returnDescriptor = [scriptObject executeAndReturnError: &errorDict];
        [scriptObject release];
    
        if (returnDescriptor != NULL)
        {
            // successful execution
            if (kAENullEvent != [returnDescriptor descriptorType])
            {
                // script returned an AppleScript result
                if (cAEList == [returnDescriptor descriptorType])
                {
                     // result is a list of other descriptors
                }
                else
                {
                    // coerce the result to the appropriate ObjC type
                }
            } 
        }
        else
        {
            // no script result, handle error here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多