将InputStream读入Data对象 [英] Reading an InputStream into a Data object

查看:74
本文介绍了将InputStream读入Data对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift 3.x中,我们通常使用Data处理二进制数据;通过它,您可以生成其他最重要的类型,并且上面有有用的功能.

In Swift 3.x, we usually handle binary data using Data; from it you can generate most other important types, and there are useful functions on it.

但是如何从InputStream创建Data?有什么好方法吗?

But how do I create a Data from an InputStream? Is there a nice way?

推荐答案

我找不到很好的方法.我们可以围绕不安全的东西创建一个漂亮的包装器:

I could not find a nice way. We can create a nice-ish wrapper around the unsafe stuff:

extension Data {
    init(reading input: InputStream) throws {
        self.init()
        input.open()
        defer {
            input.close()
        }

        let bufferSize = 1024
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        defer {
            buffer.deallocate()
        }
        while input.hasBytesAvailable {
            let read = input.read(buffer, maxLength: bufferSize)
            if read < 0 {
                //Stream error occured
                throw input.streamError!
            } else if read == 0 {
                //EOF
                break
            }
            self.append(buffer, count: read)
        }
    }
}

这是针对Swift 5的.使用测试查找完整代码(以及仅读取部分流的变体)

This is for Swift 5. Find full code with test (and a variant that reads only some of the stream) here.

这篇关于将InputStream读入Data对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆