How to get shell output in my OS X App

I have some codes to execute shell scripts:

<code>
@implementation ViewController {
    NSTask *task;
    NSPipe *pipe;
    NSFileHandle *fileHandle;
}
- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self runCommand:[[NSBundle mainBundle] pathForResource:@"Test" ofType:@"command"] arguments:@[]];
}
- (void)runCommand:(NSString *)cmd arguments:(NSArray *)args {
  
    if (task)
    {
        [task interrupt];
      
    }
    else
    {
        task = [[NSTask alloc] init];
        [task setLaunchPath:cmd];
      
        [task setArguments:args];
      
        pipe = [[NSPipe alloc] init];
        [task setStandardOutput:pipe];
      
        fileHandle = [pipe fileHandleForReading];
      
        [task launch];
        NSData *data = [fileHandle readDataToEndOfFile];
        NSString *outputString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
}
@end
</code>


The Text.command shell script logs message overtime. I can see them if I execute it in Terminal. But how can I retrive it and turn it into NSString in my OS X App. It seems like you needs to listen for some notifications to do this.

Accepted Reply

This does it:


- (void)runCommand:(NSString *)cmd arguments:(NSArray *)args
{
    task = [[NSTask alloc] init];
    [task setLaunchPath:cmd];
    [task setArguments:args];
   
    pipe = [[NSPipe alloc] init];
    [task setStandardOutput:pipe];
   
    /
    /
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didCompleteReadingFileHandle:)
                                                 name:NSFileHandleReadCompletionNotification
                                               object:[[task standardOutput] fileHandleForReading]];
   
    /
    [[pipe fileHandleForReading] readInBackgroundAndNotify];
   
    /
    [task launch];
}

Replies

The <code> snippet is used to show you guys where my codes is.

This does it:


- (void)runCommand:(NSString *)cmd arguments:(NSArray *)args
{
    task = [[NSTask alloc] init];
    [task setLaunchPath:cmd];
    [task setArguments:args];
   
    pipe = [[NSPipe alloc] init];
    [task setStandardOutput:pipe];
   
    /
    /
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didCompleteReadingFileHandle:)
                                                 name:NSFileHandleReadCompletionNotification
                                               object:[[task standardOutput] fileHandleForReading]];
   
    /
    [[pipe fileHandleForReading] readInBackgroundAndNotify];
   
    /
    [task launch];
}