1. 程式人生 > >Objective-C 執行AppleScript腳本

Objective-C 執行AppleScript腳本

url alloc use 文件中 path str lee nss app

在Objective-C裏事實上也能夠執行AppleScript

第一種方式是Source 將腳本寫到變量字符串裏

    NSAppleEventDescriptor *eventDescriptor = nil;
    NSAppleScript *script = nil;
    NSBundle *bunlde = [NSBundle mainBundle];
    NSString *scriptSource = @"tell application \"Finder\"\r"
                            "display dialog \"test\"\r"
                            "end tell";
    if (scriptSource)
    {
        script = [[NSAppleScript alloc] initWithSource:scriptSource];
        if (script)
        {
            eventDescriptor = [script executeAndReturnError:nil];
            if (eventDescriptor)
            {
                NSLog(@"%@", [eventDescriptor stringValue]);
            }
        }
    }

另外一種方式是將File, 將腳本寫到文件中

    NSAppleEventDescriptor *eventDescriptor = nil;
    NSAppleScript *script = nil;
    NSBundle *bunlde = [NSBundle mainBundle];
    NSString *scriptPath = @"/Users/exchen/Documents/test.scpt";
    if (scriptPath)
    {
        script = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:scriptPath] error:nil];
        if (script)
        {
            eventDescriptor = [script executeAndReturnError:nil];
            if (eventDescriptor)
            {
                NSLog(@"%@", [eventDescriptor stringValue]);
            }
        }
    }



Objective-C 執行AppleScript腳本