Search code examples
macoscocoanstasknsnotification

Get Notification of task progress from NSTask


Any body have idea about getting notification from NSTask while NSTask is executed. I am unzipping a zip file using NSTask and need to show the unzip data progress in a NSProgressBar. I don't found any idea for doing such task.So that i show the value in progress bar. Need help for doing this task. Thanks in advance.


Solution

  • Use NSFileHandleReadCompletionNotification, NSTaskDidTerminateNotification notifications.

    task=[[NSTask alloc] init];
    
    [task setLaunchPath:Path];
    
    NSPipe *outputpipe=[[NSPipe alloc]init];
    
    NSPipe *errorpipe=[[NSPipe alloc]init];
    
    NSFileHandle *output,*error;
    
    [task setArguments: arguments];
    
    [task setStandardOutput:outputpipe];
    
    [task setStandardError:errorpipe];
    
    output=[outputpipe fileHandleForReading];
    
    error=[errorpipe  fileHandleForReading];
    
    [task launch]; 
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:)  name: NSFileHandleReadCompletionNotification object:output];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedError:)  name: NSFileHandleReadCompletionNotification object:error];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TaskCompletion:)  name: NSTaskDidTerminateNotification object:task];
    
    //[input writeData:[NSMutableData initWithString:@"test"]];
    [output readInBackgroundAndNotify];
    
    [error readInBackgroundAndNotify];
    
    
    [task waitUntilExit];
    
    [outputpipe release];
    
    [errorpipe release];
    [task release];
    [pool release];
    
    
    /* Called when there is some data in the output pipe */
    
    -(void) receivedData:(NSNotification*) rec_not
    
    {
    
        NSData *dataOutput=[[rec_not userInfo] objectForKey:NSFileHandleNotificationDataItem];
    
        [[rec_not object] readInBackgroundAndNotify];
    
        [strfromdata release];
    
    }
    
    /* Called when there is some data in the error pipe */
    
    -(void) receivedError:(NSNotification*) rec_not
    
    {
        NSData *dataOutput=[[rec_not userInfo] objectForKey:NSFileHandleNotificationDataItem];
    
        if( !dataOutput)
    
            NSLog(@">>>>>>>>>>>>>>Empty Data");
    
        [[rec_not object] readInBackgroundAndNotify];
    
    
    }
    
    /* Called when the task is complete */
    
    -(void) TaskCompletion :(NSNotification*) rec_not
    
    {   
    
    }