Sunday, May 12, 2013

NSInputStream read example ios

read: maxLength:

Reads up to a given number of bytes into a given buffer.
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len
A data buffer. The buffer must be large enough to contain the number of bytes specified by len.
The maximum number of bytes to read.
Return Value( NSInputStream read example )
A number indicating the outcome of the operation:
  • A positive number indicates the number of bytes read;
  • 0 indicates that the end of the buffer was reached;
  • A negative number means that the operation failed.

( NSInputStream read example )

NSInteger result;
uint8_t buffer[BUFFER_LEN]; // BUFFER_LEN can be any positive integer
while((result = [iStream read:buffer maxLength:BUFFER_LEN]) != 0) {
    if(result > 0) {
        // buffer contains result bytes of data to be handled
    } else {
        // The stream had an error. You can get an NSError object using [iStream streamError]
// Either the stream ran out of data or there was an error

( NSInputStream read example )

uint8_t *buf1;
        unsigned int numBytes1;
        if ([((NSInputStream *) stream) getBuffer: &buf length: &numBytes]) {
            NSLog(@"\t\tBytes are in the buffer before Op.");

        uint8_t buffer[BUFFER_SIZE];
        int len = [((NSInputStream *) stream) read: buffer 
                                         maxLength: BUFFER_SIZE];

        uint8_t *buf2;
        unsigned int numBytes2;
        if ([((NSInputStream *) stream) getBuffer: &buf2 length: &numBytes2]) {
            NSLog(@"\t\tBytes in the buffer after Op.");

( NSInputStream read example )

- (void)stream:(NSInputStream *)iStream handleEvent:(NSStreamEvent)event {
    BOOL shouldClose = NO;
    switch(event) {
        case  NSStreamEventEndEncountered:
            shouldClose = YES;
            // If all data hasn't been read, fall through to the "has bytes" event
            if(![iStream hasBytesAvailable]) break;
        case NSStreamEventHasBytesAvailable: ; // We need a semicolon here before we can declare local variables
            uint8_t *buffer;
            NSUInteger length;
            BOOL freeBuffer = NO;
            // The stream has data. Try to get its internal buffer instead of creating one
            if(![iStream getBuffer:&buffer length:&length]) {
                // The stream couldn't provide its internal buffer. We have to make one ourselves
                buffer = malloc(BUFFER_LEN * sizeof(uint8_t));
                freeBuffer = YES;
                NSInteger result = [iStream read:buffer maxLength:BUFFER_LEN];
                if(result < 0) {
                    // error copying to buffer
                length = result;
            // length bytes of data in buffer
            if(freeBuffer) free(buffer);
        case NSStreamEventErrorOccurred:
            // some other error
            shouldClose = YES;
    if(shouldClose) [iStream close];