views:

449

answers:

4

I have seen this thread on how to execute terminal commands from within a Cocoa app. But I want to actually launch Terminal.app to a specified directory.

I know that the following does not work:

[[NSWorkspace sharedWorkspace] openFile:folderPath withApplication:@"Terminal"];

Terminal tries to actually open the folder as a file.

Is this something I have to use AppleScript for?

Any ideas?

+2  A: 

Not sure if there's a way to do it in plain cocoa, but in applescript it's fairly trivial

tell application "Terminal" to do script "cd ~/Desktop"
cobbal
thanks, you and woofy solved it!
Corey Floyd
A: 

I don't really know AppleScript, but I bet you could use it for this.

If the terminal directory is the same each time, you could just make an executeable .sh file with a cd command in it and make that the openFile argument.

phoebus
+6  A: 

You could use AppleScript from Cocoa like this:

NSString *s = [NSString stringWithFormat:
     @"tell application \"Terminal\" to do script \"cd %@\"", folderPath];

NSAppleScript *as = [[NSAppleScript alloc] initWithSource: s];
[as executeAndReturnError:nil];

AppleScript script was taken from cobbal. Thanks mate!

Woofy
perfect, thanks!
Corey Floyd
Although perhaps overkill for this use, the Scripting Bridge (http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ScriptingBridgeConcepts/Introduction/Introduction.html) is a good solution for communicating with external apps via AppleScript from within Objective-C apps.
Barry Wark
be careful of folders with a quotation marks or spaces in them though
cobbal
A: 

The existing answers suggesting using the cd command are great. Additionally, I recommend checking out the source to the app cdto for a great example. Cdto is a fast mini application that opens a Terminal.app window cd'd to the front most finder window. This app is designed (including it's icon) to placed in the finder window's toolbar.

Joey Hagedorn