title: NSStream, getting percentage of bytes read
body: <p>I am uploading a file to a server, using NSStream APIs to read in chunks. I'm trying to display a progress bar showing upload progress. I'm unable to find a reliable solution for determining the number of bytes read into the file. Changing file and chunk size, I still keep getting either the total bytes, or something strange such as 93 or 212 for bytes read. Does anyone have any tips for trying to accomplish this? It seems like it should be simple.</p>
  
  <pre><code>  // create the write stream
      NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:uploadTempFilename append:NO];
      [outputStream open];
  
      const char *UTF8String;
      size_t writeLength;
      UTF8String = [multipartBegin UTF8String];
      writeLength = strlen(UTF8String);
  
      size_t __unused actualWrittenLength;
      actualWrittenLength = [outputStream write:(uint8_t *)UTF8String maxLength:writeLength];
  
      NSLog(@"actualWrittenLength1 %d bytes)", actualWrittenLength);//this will be 908
      // open the input stream
      const size_t bufferSize = 128 ;
      size_t readSize = 0;
      uint8_t *buffer = (uint8_t *)calloc(1, bufferSize);
  
      [inImageStream open];
      while ([inImageStream hasBytesAvailable]) {
          if (!(readSize = [inImageStream read:buffer maxLength:bufferSize])) {
              break;
          }
  
  
       size_t __unused actualWrittenLength;
  
  
          actualWrittenLength = [outputStream write:buffer maxLength:readSize];
  
          NSLog(@"actualWrittenLength2 %d bytes)", actualWrittenLength);//this always outputs 128, until the last call which will be something like 22
  
  
      }
  
      //NSLog(@"NSStreamFileCurrentOffsetKey %d", [outputStream valueForKey:NSStreamFileCurrentOffsetKey]);
      [inImageStream close];
      free(buffer);
  
  
      UTF8String = [multipartEnd UTF8String];
      writeLength = strlen(UTF8String);
      actualWrittenLength = [outputStream write:(uint8_t *)UTF8String maxLength:writeLength];
  
      NSLog(@"actualWrittenLength3 %d bytes)", actualWrittenLength);//this will always be 42
  
  [outputStream close];
  
  
  
      NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:uploadTempFilename];
  
      [HTTPRequest setContentType:contentType];
      return [HTTPRequest performMethod:@"POST" onURL:url withInputStream:inputStream knownContentSize:fileSize];
  </code></pre>