我想说我想通过Objective C应用程序运行curl -o http://example.com/file.zip
我希望有一个标签或文本框,其中包含在命令运行时更新的下载状态。也许这可以使用dispatch_async实现,但现在确定如何。在标记为重复之前,我找到的方法,运行命令,之后完成后获得输出。我希望在它运行时得到输出,有点像终端模拟器。
答案 0 :(得分:3)
您需要使用NSPipe
属性将NSTask
与standardOutput
相关联,然后注册接收可用数据通知。
@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