Monday, April 29, 2013

NSFileHandle NSFileHandleDataAvailableNotification example ios


NSFileHandleDataAvailableNotification


This notification is posted when the file handle determines that data is currently available for reading in a file or at a communications channel. The observers can then issue the appropriate messages to begin reading the data. To cause the posting of this notification, you must send either waitForDataInBackgroundAndNotify or waitForDataInBackgroundAndNotifyForModes: to an appropriate NSFileHandle object.[NSFileHandle NSFileHandleDataAvailableNotification]
The notification object is the NSFileHandle object that sent the notification. This notification does not contain a userInfo dictionary.
Example of [NSFileHandle NSFileHandleDataAvailableNotification]

/**
 * Fired whenever new data becomes available on STDERR
 *
 * @private
 */

-(void) errorData: (NSNotification *) notification
{
    NSFileHandle *fileHandle = (NSFileHandle*) [notification object];
    NSData *data = [fileHandle availableData];

    if ([data length]) {
        // consume data
        // ...

        [fileHandle waitForDataInBackgroundAndNotify];
    } else {
        // EOF was hit, remove observer - NSFileHandleDataAvailableNotification
        [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleDataAvailableNotification object:fileHandle];
    }
}