views:

169

answers:

2

Can someone show a quick example on how to use NSTask and NSPipe in conjunction to do this:

Charlie AI - run through terminal to comunicate with the AI

I want to create a nice GUI for it using xcode and objective c. I want to have 2 NSTextFields for the charlie's response and user input. Then have a send button to send the user input to the command line, then get the charlie's response and post it in the NSTextField.

I can handle the GUI stuff (NSTextField, ect.) But I need help with the objective-c coding part.

Thanks!

Elijah

+1  A: 

Apple have some nice sample code that shows how to do most of that... http://developer.apple.com/mac/library/samplecode/Moriarity/

TaskWrapper.m contains all the clever stuff, but since you want to be able to send data to the task, you'll need to extend it a little, like so:

[task setStandardInput: [NSPipe pipe]];

To send input to the task, you can then do:

[[[task standardInput] fileHandleForWriting] writeData: ...];

To turn the NSTextField's value into data, you can do something like this:

NSData *data = [[inputTextField stringValue] dataUsingEncoding:NSUTF8StringEncoding];

...and to set the current working directory for your sub-task, use [NSTask setCurrentDirectoryPath:]

e.g.

[task setCurrentDirectoryPath:@"/blah/blah"];
[task setLaunchPath:@"/blah/blah/server.sh"];

.... (other setup code)

[task launch];
Nick Dowell
1 more thing...how would I send "cd /blah/blah" and then "./server.sh" to start charlie?
Elijah W.
Updated my response to show how to do that... hope it helps :-)
Nick Dowell
Also, how do get the data from the terminal after I sent something? I'm confused with how moriarity does it.
Elijah W.
+1  A: 

There's also AMShellWrapper sample code which improves on moriarity.

http://www.harmless.de/cocoa-code.php

ceeit