如何将NSInputStream转换为NSString或如何读取NSInputStream

Min*_*imi 2 objective-c nsinputstream ios

我正在尝试将输入流转换为字符串。我要转换的输入流是NSURLRequest.HTTPBodyStream,显然将httpbody设置为null,并在发出请求后将其替换为该流。我该怎么做呢?这是我到目前为止的内容:

#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++;
        }
    }
Run Code Online (Sandbox Code Playgroud)

当我打印字符串时,它要么总是为空,要么包含单个字符,甚至不输出null。有什么建议么?

Min*_*imi 5

得到它了。我尝试访问的流尚未打开。即使这样,它还是只读的。因此,我制作了一个副本,然后将其打开。但是,这仍然不对,我一次只读取一个字节(单个字符)。所以这是最终的解决方案:

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);
}
Run Code Online (Sandbox Code Playgroud)