How to convert NSInputStream to NSString or how to read NSInputStream

流过昼夜 提交于 2019-12-06 09:20:38

Got it. The stream that I tried to access hadn't been opened. Even then, it was read only. So I made a copy of it and then opened it. This still wasn't right though, I was only reading a byte at a time (a single character). So here's the final solution:

NSInputStream *stream = r.HTTPBodyStream;
uint8_t byteBuffer[4096];

[stream open];
if (stream.hasBytesAvailable)
{
    NSLog(@"bytes available");
    NSInteger bytesRead = [stream read:byteBuffer maxLength:sizeof(byteBuffer)]; //max len must match buffer size
    NSString *stringFromData = [[NSString alloc] initWithBytes:byteBuffer length:bytesRead encoding:NSUTF8StringEncoding];

    NSLog(@"another pathetic attempt: %@", stringFromData);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!