我似乎无法监视我的 NSTask 命令的输出。据我了解,必须使用 NSNotificationCenter。我尝试运行的终端命令使用各种加密方法从我的安全服务器下载文件(在 Objective-c 中重写它会很痛苦)。我将需要监控结果,以便我可以收到已完成下载的百分比。
这是我到目前为止所拥有的
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
task = [[NSTask alloc] init];
pipe = [[NSPipe alloc] init];
NSDictionary *defaultEnvironment = [[NSProcessInfo processInfo] environment];
NSMutableDictionary *environment = [[NSMutableDictionary alloc] initWithDictionary:defaultEnvironment];
[environment setObject:@"YES" forKey:@"NSUnbufferedIO"];
[task setEnvironment:environment];
[task setLaunchPath:[[NSBundle mainBundle] pathForResource:@"servDecryptor" ofType:nil]];
[task setArguments:[NSArray arrayWithArray:arguments]];
[task setStandardOutput:pipe];
fh = [pipe fileHandleForReading];
[nc addObserver:self
selector:@selector(ready:)
name:NSFileHandleReadCompletionNotification
object:fh];
[nc addObserver:self
selector:@selector(decFinished:)
name:NSTaskDidTerminateNotification
object:task];
[task launch];
[fh readInBackgroundAndNotify];
和
//Ready method
[[pipe fileHandleForReading] readInBackgroundAndNotify];
NSData *d;
d = [[note userInfo] valueForKey:NSFileHandleNotificationDataItem];
if ([d length] > 0) {
NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
}
请注意:下载开始并继续进行,而无需进入我的第二种方法。但是,在下载完成并且该过程结束后,应用程序会崩溃。