iphone – help needed on writing NSData to output stream using NSStream in objective c – Education Career Blog

i using the following code which writes the file from a path to an output stream but every time i run the code, it always write 131768 bytes to the stream regards of my file size(8MB or 5MB or etc). Can someone please check for me? i can’t seems to find the problem. Or it there other ways to do it? I’m using NSStream with the following code:

NSString *filesContent = NSString alloc initWithContentsOfFile:myMediaFile;           // myMediaFile is a path to my file eg. .../Documents/myvideo.mp4/

NSData *data =  filesContent dataUsingEncoding:NSASCIIStringEncoding        allowLossyConversion:YES;

const uint8_t *buf = data bytes;

NSUInteger length = data length;
 NSLog(@"datalen = %d",length);
 NSInteger nwritten = outputStream write:buf maxLength:length;

 if (-1 == nwritten) {
  NSLog(@"Error writing to stream %@: %@", outputStream, outputStream streamError);
  NSLog(@"Wrote %ld bytes to stream %@.", (long long)nwritten, outputStream);


This is a duplicate of How to use NSOutputStream’s write message?, not that I’m surprised you didn’t find that one.

Bottom line; the write:maxLength: method isn’t necessarily going to write all the data you pass to it all at once. There is buffering involved and, thus, you’ll likely need to loop writing data as space is available on the output stream.

Note that by “loop”, I do not mean “poll”.

Leave a Comment