Monday, April 29, 2013

NSFileHandle NSFileHandleReadCompletionNotification example ios


NSFileHandleReadCompletionNotification


This notification is posted when the file handle reads the data currently available in a file or at a communications channel. It makes the data available to observers by putting it in the userInfodictionary. To cause the posting of this notification, you must send eitherreadInBackgroundAndNotify or readInBackgroundAndNotifyForModes: to an appropriateNSFileHandle object.[NSFileHandle NSFileHandleReadCompletionNotification]
The notification object is the NSFileHandle object that sent the notification. The userInfo dictionary contains the following information:
Key
Value
NSFileHandleNotificationDataItemAn NSData object containing the available data read from a socket connection
@"NSFileHandleError"An NSNumber object containing an integer representing the UNIX-type error which occurred
Example of [NSFileHandle NSFileHandleReadCompletionNotification]
{ 
    //.....
    [segmentTask setStandardInput:[encodeTask standardOutput]];
    [segmentTask setStandardOutput:[NSPipe pipe]];

    NSFileHandle *file = [[segmentTask standardOutput] fileHandleForReading];
    [file readInBackgroundAndNotify];
//[NSFileHandle NSFileHandleReadCompletionNotification]
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getData:) name:NSFileHandleReadCompletionNotification object:file];

//.....
}

- (void) getData: (NSNotification *)aNotification
{
    NSData *data = [[aNotification userInfo] objectForKey:@"NSFileHandleNotificationDataItem"];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%@", string);
    [[aNotification object] readInBackgroundAndNotify];
}