Pergunta

I am trying to launch an application and open a file in it through applescript. I was able to do it from the Apple Script Editor. This is th escript i wrote:

set AppPath to "<My App Path.app>"
tell application AppPath
    if it is running then
        activate
    else
        launch
    end if
    tell application AppPath to open POSIX file "<My File Path>"
end tell

If the application was running in background, launch alone was unable to bring it to the foregraound (above the script editor). And if the application was not running, activate was unable to show splash screen. That's why, I used bot launch and activate.

The script is working fine. But I need the script in my c++ program. The app path and the file path will be decided on runtime. So i was generating the script as NSAppleScript and executing the script. And the generated NSApplescript looks as follows:

do shell script "osascript -e 'set AppPath to \"<My App Path.app>\"' 
-e 'tell application AppPath' -e 'if it is running then' -e 'activate' 
-e 'else' -e 'launch' -e 'endif' 
-e 'tell application AppPath to open POSIX file \"<My File Path>\"'"

All the above code is in a single line, I broke it for readability. I get an error saying variable e is not defined. This is not getting executed.

The code I use to generate this script is:

NSMutableString *script = [NSMutableString stringWithCapacity:512];
[script appendString:@"do shell script \"osascript "];
[script appendString:@"-e 'set AppPath to \\\""];
[script appendString:pathToApp];
[script appendString:@"\\\"'"];
[script appendString:@" -e 'tell application AppPath'"];
[script appendString:@" -e 'if it is running then'"];
[script appendString:@" -e 'activate'"];
[script appendString:@" -e 'else'"];
[script appendString:@" -e 'launch'"];
[script appendString:@" -e 'end if'"];
[script appendString:@" -e 'tell application AppPath to open POSIX file \\\""];
[script appendString:pathToFile];
[script appendString:@"\\\"'"];
[script appendString:@"\"\r"];

I added spaces before -e as user309603 suggested. Now I get a new error:

error "266:266: syntax error: Expected end of line, etc. but found end of script. (-2741)" number 1

Foi útil?

Solução

The tell block has to be closed in the last line (like you wrote it in AS Editor)

[script appendString:@" -e 'end tell'"];

and btw in the second last line the tell application AppPath to part is not needed.

Outras dicas

Don't use code generation. Just don't. If you think you need code generation, you're doing it wrong. osascript and NSAppleScript both allow you to pass parameters to existing AppleScripts.

For something as simple as opening a file, you don't need AppleScript at all. Use NSWorkspace or LaunchServices.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top