NSTask and NSPipe example to comunicate with the command line objective-c

objectiveccoder001 picture objectiveccoder001 · Jul 9, 2010 · Viewed 7.4k times · Source

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

Answer

Nick Dowell picture Nick Dowell · Jul 10, 2010

Apple has some nice sample code that shows how to do most of that.

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];