views:

726

answers:

2

I'm creating an NSInputStream from an NSData object but once created the stream reports NO for hasBytesAvailable:

NSData* data = [outputStream propertyForKey: NSStreamDataWrittenToMemoryStreamKey]; 
NSLog(@"creating stream with data 0x%x length %d", [data bytes], [data length]);
NSInputStream *insrm = [[NSInputStream alloc] initWithData:data];
[insrm open];

uint8_t* buf = NULL;
NSUInteger len;
BOOL result = [insrm getBuffer:&buf length:&len];
BOOL hasbytes = [insrm hasBytesAvailable];
NSLog(@"getBuffer:%d hasBytes:%d", result, hasbytes);
NSLog(@"created inputstream data %d len %d", buf, len);

Log:

[26797:20b] creating stream with data 0x7050000 length 34672
[26797:20b] getBuffer:0 hasBytes:0
[26797:20b] created inputstream data 0 len 0

What am I missing here?

+2  A: 

This code will work for reading your stream:

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

getBuffer:length: will return YES if you do not open the stream. However, it will not initially have valid values in buf or len. I think this is due to the fact that it is a non-blocking operation. Presumably values will be filled in later.

In any case, if you want to block, use what I have above. If you do not want to block, you should schedule the input stream on the run loop and implement the delegate method stream:handleEvent:. However, even this does not guarantee that you will never block. Instead you might want to look for a library that offers another layer of abstraction and handles the stream on a separate thread for you.

gerry3
I haven't looked at this for a while but I remember it was worse than the call just not working. The `getBuffer:length:` seemed to corrupt the stream and future reads failed. See how `hasBytesAvailiable` fails? But it would work just fine if I put it before the `getBuffer:length:`. Anyway, everything started working just fine once I took the call out. It was just in there for debug purposes anyway.
gabe
A: 

How you get it working can you share the code snippets, Thanks, Aks..

Aks
This is not an answer, this is a comment.
Shaggy Frog
U got any way to solve your problem, how to upload the data with NStream ..... If yes could you please help me out :(Thanks,
Aks