如何以编程方式创建和保存applescript文件

时间:2013-12-18 12:45:08

标签: objective-c file-io applescript osx-mavericks

我想为应用程序创建一个AppleScript菜单文件,我需要编辑该文件,因此我在文本文件中有脚本,我编辑了文件并将其保存为脚本文件,但不幸的是它没有检测为脚本文件通过应用程序“Outlook Mac 2011”,甚至当我将此文件打开到脚本编辑器并尝试保存它的投掷错误无法保存时请帮助我这个

        userpath = [paths objectAtIndex:0];
        userpath = [userpath stringByAppendingString:@"/Microsoft User Data/Outlook Script Menu Items/"];
        userpath = [userpath stringByAppendingString:@"Create New Conference Event.scptd"];

        [[NSFileManager defaultManager] createFileAtPath:userpath contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

        NSDictionary* errorDis = [[NSDictionary alloc] init];
        NSAppleScript *script = [[NSAppleScript alloc] initWithContentsOfURL: [NSURL fileURLWithPath:userpath] error:&errorDis];

然后我正在尝试编译已编辑的文件

NSDictionary* errors = [NSDictionary dictionary];
        NSAppleScript* appleScript = [[NSAppleScript alloc] initWithContentsOfURL:url error:&errors];
        [appleScript compileAndReturnError:&errors];

我收到此错误

Printing description of errors:
{
    NSAppleScriptErrorNumber = "-43";
}

1 个答案:

答案 0 :(得分:1)

假设您的'内容'是NSString。

只需将 scptd 扩展名更改为 scpt

userpath = [userpath stringByAppendingString:@"Create New Conference Event.scpt"];

        [[NSFileManager defaultManager] createFileAtPath:userpath contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

似乎只是这样做会保存一个在打开时有效的编译文件。

UPDATE *


另一种方法是使用NSApplescript运行脚本来存储outlook脚本。

示例代码:

 NSString * scriptContent = @"say \"hello\"";
    NSString * scriptPath =@"\"/Users/USERNAME/Downloads/theScript.scpt\"";

    NSString * content =[NSString  stringWithFormat: @"set script_text to MakeScript()\n my RunMaker(script_text)\n on RunMaker(script_text)\n set file_spec to (%@) \n store script script_text in file_spec replacing yes \n end RunMaker \n on MakeScript() \n script \n  %@ \n end script \nend MakeScript",scriptPath,scriptContent];

    NSLog(@" content %@", content);

    NSDictionary* errorDis = [[NSDictionary alloc] init];
    NSAppleScript *script = [[NSAppleScript alloc] initWithSource:content];
    [script executeAndReturnError:&errorDis];

     NSLog(@" errorDis %@", errorDis);

代码编译并运行为:

set script_text to MakeScript()
 my RunMaker(script_text)
 on RunMaker(script_text)
 set file_spec to ("/Users/USERNAME/Downloads/theScript.scpt") 
 store script script_text in file_spec replacing yes 
 end RunMaker 
 on MakeScript() 
 script 
  say "hello" 
 end script 
end MakeScript

下载中保存名为 theScript.scpt 的脚本文件。 (根据我现有的AppleScript,它可以缩短)