Showing posts with label NSFileHandle example. Show all posts
Showing posts with label NSFileHandle example. Show all posts

Monday, April 29, 2013

NSFileHandle NSFileHandleReadToEndOfFileCompletionNotification example ios


NSFileHandleReadToEndOfFileCompletionNotification


This notification is posted when the file handle reads all data in the file or, if a communications channel, until the other process signals the end of data. It makes the data available to observers by putting it in the userInfo dictionary. [NSFileHandle NSFileHandleReadToEndOfFileCompletionNotification]
To cause the posting of this notification, you must send either readToEndOfFileInBackgroundAndNotify or readToEndOfFileInBackgroundAndNotifyForModes: to an appropriate NSFileHandleobject.
The notification object is the NSFileHandle object that sent the notification. The userInfodictionary 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 NSFileHandleReadToEndOfFileCompletionNotification]

- (void)launch {
    NSTask *task = [[[NSTask alloc] init] autorelease];
    [task setLaunchPath:@"/path/to/command"];
    [task setArguments:[NSArray arrayWithObjects:..., nil]];
    NSPipe *outputPipe = [NSPipe pipe];
    [task setStandardOutput:outputPipe];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readCompleted:) name:NSFileHandleReadToEndOfFileCompletionNotification object:[outputPipe fileHandleForReading]];
    [[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
    [task launch];
}
// NSFileHandleReadToEndOfFileCompletionNotification handler.
- (void)readCompleted:(NSNotification *)notification {
    NSLog(@"Read data: %@", [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem]);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadToEndOfFileCompletionNotification object:[notification object]];
}

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];
}

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];
    }
}

NSFileHandle NSFileHandleConnectionAcceptedNotification example ios


NSFileHandleConnectionAcceptedNotification


This notification is posted when an NSFileHandle object establishes a socket connection between two processes, creates an NSFileHandle object for one end of the connection, and makes this object available to observers by putting it in the userInfo dictionary. To cause the posting of this notification, you must send either acceptConnectionInBackgroundAndNotify or acceptConnectionInBackgroundAndNotifyForModes: to an NSFileHandle object representing a server stream-type socket. [NSFileHandle NSFileHandleConnectionAcceptedNotification]
The notification object is the NSFileHandle object that sent the notification. The userInfodictionary contains the following information:
Key
Value
NSFileHandleNotificationFileHandleItemThe NSFileHandle object representing the “near” end of a socket connection
@"NSFileHandleError"An NSNumber object containing an integer representing the UNIX-type error which occurred
example of [NSFileHandle NSFileHandleConnectionAcceptedNotification]
-(void)createSocket 
{
    // create socket and wait for events to come in
    NSSocketPort* serverSock = [[NSSocketPort alloc] initWithTCPPort: 1234];
    socketHandle = [[NSFileHandle alloc] initWithFileDescriptor: [serverSock socket]
                                                 closeOnDealloc: NO];
// NSFileHandleConnectionAcceptedNotification
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(newConnection:) 
                                                 name: NSFileHandleConnectionAcceptedNotification
                                               object: socketHandle];

    [socketHandle acceptConnectionInBackgroundAndNotify];
}

- (void)newConnection:(NSNotification*)notification
{
    NSLog(@"connection accepted");

    NSDictionary* userInfo = [notification userInfo];
    NSFileHandle* remoteFileHandle = [userInfo objectForKey:
                                      NSFileHandleNotificationFileHandleItem];

    if([[userInfo allKeys] containsObject:@"NSFileHandleError"]){
        NSNumber* errorNo = [userInfo objectForKey:@"NSFileHandleError"];
        if( errorNo ) {
            NSLog(@"NSFileHandle Error: %@", errorNo);
            return;
        }
    }

    [socketHandle acceptConnectionInBackgroundAndNotify];


    [[NSNotificationCenter defaultCenter] addObserver:self 
       selector: @selector(processSocketData:)
           name: NSFileHandleReadCompletionNotification
         object: remoteFileHandle];

    // Send a message to the client, acknowledging that the connection was accepted
    [remoteFileHandle writeData: [@"OK" dataUsingEncoding: NSASCIIStringEncoding]];

    [remoteFileHandle readInBackgroundAndNotify];
}

Saturday, April 27, 2013

NSFileHandle writeData example ios


writeData:

Synchronously writes the specified data to the receiver.
- (void)writeData:(NSData *)data
Parameters
data
The data to be written.
Discussion of [NSFileHandle writeData]
If the receiver is a file, writing takes place at the file pointer’s current position. After it writes the data, the method advances the file pointer by the number of bytes written. [NSFileHandle writeData]This method raises an exception if the file descriptor is closed or is not valid, if the receiver represents an unconnected pipe or socket endpoint, if no free space is left on the file system, or if any other writing error occurs.

Example of [NSFileHandle writeData]

Write to file.
----------------------------------------------------------------------------
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToFileOffset:30]; 
NSLog(@"offset : %llu", [file offsetInFile]); 

NSData *databuffer = [file readDataOfLength:10];
[file seekToFileOffset:50]; 
[file writeData :databuffer];

[file closeFile]; 

----------------------------------------------------------------------------
- (NSString *)outputFromExporter:(COExporter *)exporter input:(NSString *)input {
  NSString *exportedString = nil;
  NSString *path = [exporter path];
  NSTask *task = [[NSTask alloc] init];

  NSPipe *writePipe = [NSPipe pipe];
  NSFileHandle *writeHandle = [writePipe fileHandleForWriting];
  NSPipe *readPipe = [NSPipe pipe];
  NSFileHandle *readHandle = [readPipe fileHandleForReading];

  NSMutableData *outputData = [[NSMutableData alloc] init];
  NSData *readData = nil;

  // Set the launch path and I/O for the task
  [task setLaunchPath:path];
  [task setStandardInput:writePipe];
  [task setStandardOutput:readPipe];

  // Launch the exporter, it will convert the raw OPML into HTML, Plaintext, etc
  [task launch];

  // Write the raw OPML representation to the exporter's input stream
  [writeHandle writeData:[input dataUsingEncoding:NSUTF8StringEncoding]];
  [writeHandle closeFile];

  while ((readData = [readHandle availableData]) && [readData length]) {
    [outputData appendData:readData];
  }

  exportedString = [[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding];
  return exportedString;
}