运行 在 Objective c 上执行 shell 命令并同时获得输出
Run a shell command on Objective c and simultaneously get output
假设我想通过 Objective C 应用 运行 curl -o http://example.com/file.zip
并且我想要一个包含下载状态的标签或文本框,当命令为 运行宁。也许这可以使用 dispatch_async 来实现,但现在确定如何实现。在标记为重复之前,我找到的方法,运行 命令,以及 after 它已经完成你得到输出。我想在 运行ning 时获得输出,有点像终端仿真器。
您需要使用 standardOutput
属性 将 NSPipe
连接到 NSTask
并注册以接收 可用数据通知。
@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
假设我想通过 Objective C 应用 运行 curl -o http://example.com/file.zip
并且我想要一个包含下载状态的标签或文本框,当命令为 运行宁。也许这可以使用 dispatch_async 来实现,但现在确定如何实现。在标记为重复之前,我找到的方法,运行 命令,以及 after 它已经完成你得到输出。我想在 运行ning 时获得输出,有点像终端仿真器。
您需要使用 standardOutput
属性 将 NSPipe
连接到 NSTask
并注册以接收 可用数据通知。
@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