从Cocoa应用程序运行AppleScript

Fáb*_*rez 12 cocoa applescript objective-c

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

我已经尝试过NSAppleScript类,但没有成功.

此外,Apple是否允许这样做?

Fáb*_*rez 12

解决了!

Xcode没有将我的脚本文件保存到应用程序的资源路径中.要从Cocoa Application运行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];
Run Code Online (Sandbox Code Playgroud)


reg*_*633 11

您提到xcode没有将脚本保存到您应用的资源路径.那是正确的.你必须告诉xcode这样做.首先将编译后的脚本添加到项目中.然后打开目标并找到"复制捆绑资源"操作.将脚本从文件列表拖到该操作中.这样您的脚本就会自动复制到应用程序的资源中,因此您无需手动执行此操作.

每当我在cocoa应用程序中使用已编译的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;
}
Run Code Online (Sandbox Code Playgroud)


Huy*_*Inc 5

来自苹果文档 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];

    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
    }
}
Run Code Online (Sandbox Code Playgroud)