Skip to content

Instantly share code, notes, and snippets.

@edwardean
Forked from fel-cesar/NSData+stream.m
Created November 24, 2018 14:09
Show Gist options
  • Save edwardean/65a852816a1557d54a7d4f9512ebedc4 to your computer and use it in GitHub Desktop.
Save edwardean/65a852816a1557d54a7d4f9512ebedc4 to your computer and use it in GitHub Desktop.
Convert NSInputStream to NSData
+(NSData*) dataWithInputStream:(NSInputStream*) stream {
NSMutableData * data = [NSMutableData data];
[stream open];
NSInteger result;
uint8_t buffer[1024]; // BUFFER_LEN can be any positive integer
while((result = [stream read:buffer maxLength:1024]) != 0) {
if(result > 0) {
// buffer contains result bytes of data to be handled
[data appendBytes:buffer length:result];
} else {
// The stream had an error. You can get an NSError object using [iStream streamError]
if (result<0) {
[NSException raise:@"STREAM_ERROR" format:@"%@", [stream streamError]];
}
}
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment