【问题标题】:How to convert NSInputStream to NSString or how to read NSInputStream如何将 NSInputStream 转换为 NSString 或如何读取 NSInputStream
【发布时间】:2016-12-22 22:51:48
【问题描述】:

我正在尝试将输入流转换为字符串。我要转换的输入流是 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++;
        }
    }

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

【问题讨论】:

    标签: ios objective-c nsinputstream


    【解决方案1】:

    知道了。我试图访问的流尚未打开。即便如此,它也是只读的。所以我复制了它然后打开它。但这仍然不对,我一次只读取一个字节(单个字符)。所以这是最终的解决方案:

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

    【讨论】:

    • 您可能希望在此处设置与stackoverflow.com/questions/41293656/… 相同的byteBuffer 大小修复;这样当其他人看到这个答案时,他们不会感到困惑/不要复制损坏的代码。
    • 是的,你是对的,我实际上有错误,因为我后来才发现。谢谢指出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 2014-09-10
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多