Sunday, May 12, 2013

NSInputStream hasBytesAvailable example ios


Returns a Boolean value that indicates whether the receiver has bytes available to read.
- (BOOL)hasBytesAvailable
Return Value
YES if the receiver has bytes available to read, otherwise NO. May also return YES if a read must be attempted in order to determine the availability of bytes.
( NSInputStream hasBytesAvailable example )
NSInputStream *insrm = [[NSInputStream alloc] initWithData:data];
[insrm open];

while ([insrm hasBytesAvailable]) {
 uint8_t buf[128];
 NSUInteger bytesRead = [insrm read:buf maxLength:128];
 NSLog(@"read %d bytes",bytesRead);
( NSInputStream hasBytesAvailable 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];
( NSInputStream hasBytesAvailable example )
while (![iStream hasBytesAvailable])
uint8_t buffer[1024];
int len;
NSString *str = @"";

while ([iStream hasBytesAvailable]) 
    len = [iStream read:buffer maxLength:sizeof(buffer)];
    if (len > 0) 
        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSISOLatin1StringEncoding];

        if (output != nil) 
            str = [str stringByAppendingString:output];
NSLog(@"Response: %@", str);