0
我似乎無法監控我的NSTask命令的輸出。據我瞭解,必須使用NSNotificationCenter。我嘗試運行的終端命令使用各種加密方法從我的安全服務器上下載文件(在objective-c中重寫此操作將是一個很大的麻煩)。我將需要監視結果,以便我可以收到已完成下載的百分比。NSTask實時監控輸出
這裏是我迄今爲止
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];
}
請注意:下載開始,沒有踏進我的第二個方法的進展。但是,下載完成並且進程結束後,應用程序崩潰。
很好用!謝謝! –