在Objective c上运行shell命令并同时获得输出

时间:2017-07-19 17:05:51

标签: objective-c bash macos shell nstask

我想说我想通过Objective C应用程序运行curl -o http://example.com/file.zip我希望有一个标签或文本框,其中包含在命令运行时更新的下载状态。也许这可以使用dispatch_async实现,但现在确定如何。在标记为重复之前,我找到的方法,运行命令,之后完成后获得输出。我希望在它运行时得到输出,有点像终端模拟器。

1 个答案:

答案 0 :(得分:3)

您需要使用NSPipe属性将NSTaskstandardOutput相关联,然后注册接收可用数据通知。

@interface TaskMonitor: NSObject
@property NSPipe *outputPipe;
@end

@implementation TaskMonitor

-(void)captureStandardOutput:(NSTask *)process {

  self.outputPipe = [NSPipe new];
  process.standardOutput = self.outputPipe;

  //listen for data available
  [self.outputPipe.fileHandleForReading waitForDataInBackgroundAndNotify];

  [[NSNotificationCenter defaultCenter] addObserverForName:NSFileHandleDataAvailableNotification object:self.outputPipe.fileHandleForReading queue:nil usingBlock:^(NSNotification * _Nonnull note) {

    NSData *output = self.outputPipe.fileHandleForReading.availableData;
    NSString *outputString = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];

    dispatch_async(dispatch_get_main_queue(), ^{
      // do something with the string chunk that has been received
      NSLog(@"-> %@",outputString);
    });

    //listen again...
    [self.outputPipe.fileHandleForReading waitForDataInBackgroundAndNotify];

  }];

}

@end