How to convert NSInputStream to NSString or how to read NSInputStream

不羁岁月 提交于 2019-12-22 14:42:00

问题


I'm trying to convert my input stream to a string. The input stream I'm trying to convert is NSURLRequest.HTTPBodyStream, apparently the httpbody is set to null and replaced with the stream after you make the request. how do I go about doing this? This is what I have so far:

#define MAX_UTF8_BYTES 6
    NSString *utf8String;
    NSMutableData *_data = [[NSMutableData alloc] init]; //for easy 'appending' bytes

    int bytes_read = 0;
    while (!utf8String) {
        if (bytes_read > MAX_UTF8_BYTES) {
            NSLog(@"Can't decode input byte array into UTF8.");
            break;
        }
        else {
            uint8_t byte[1];
            [r.HTTPBodyStream read:byte maxLength:1];
            [_data appendBytes:byte length:1];
            utf8String = [NSString stringWithUTF8String:[_data bytes]];
            bytes_read++;
        }
    }

When I print the string it's either always empty or contains a single character, doesn't even print null. Any suggestions?


回答1:


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);
}


来源:https://stackoverflow.com/questions/41292779/how-to-convert-nsinputstream-to-nsstring-or-how-to-read-nsinputstream

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