Knowing that data from an NSStream is complete

256 Views Asked by At

I'am sending chunks of UIImage data over MCSession with an NSStream.

When I get bytes

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {

   if (eventCode == NSStreamEventHasBytesAvailable) {

      // read data and append to self.data
      // how to know that self.data can be used to create UIImage

   }

}

I append them to a mutable data instance. The problem is how to know that the accumulated data represents a full image, so I can use -[UIImage initWithData:] to create it?

2

There are 2 best solutions below

3
Lance On

You should watch for NSStreamEventEndEncountered

5
jscs On

The stream has no knowledge of its contents. If you can't rely on the stream ending to tell you that the data is complete, then you either need to use/create some protocol for the transmission that includes a "finished" signal, or just try to create the image and take appropriate action if that fails.