执行在iOS中的readDataToEndOfFile方法停止

时间:2014-04-08 06:17:56

标签: ios nstask nsfilehandle

应用程序执行在" readDataToEndOfFile"之后停止/挂起方法执行。请找到以下代码,如何解决此问题

    - (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/sbin/tcpdump"];
    [task setArguments: [[NSArray alloc] initWithObjects:@"-l", @"-i",@"en1",@"-A",@"-vvv",@"host",@"www.facebook.com", nil]];

    NSPipe *pipe= [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *fileHandle = [pipe fileHandleForReading];

    [task launch];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name:NSFileHandleDataAvailableNotification object:fileHandle];
    [fileHandle waitForDataInBackgroundAndNotify];

}


- (void)receivedData:(NSNotification *)notif {

    NSFileHandle *fileHandle=notif.object;
    NSData *data = [fileHandle readDataToEndOfFile];

    NSString *output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog(@"result: %@", output);
}

1 个答案:

答案 0 :(得分:0)

尝试使用availableData代替readDataToEndOfFile

NSFileHandle *fileHandle=notif.object;
NSData *data = [fileHandle availableData];
if (data)
{
// do something
}