Reading an InputStream into a Data object

2019-04-10 13:06发布

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.

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

2条回答
劫难
2楼-- · 2019-04-10 13:27

above the code, It can be infinite loop. When I convert httpbodyInpustream to data, it happend. So I add a condition.

extension Data {
    init(reading input: InputStream) {
        self.init()
        input.open()

        let bufferSize = 1024
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        while input.hasBytesAvailable {
            let read = input.read(buffer, maxLength: bufferSize)
            if (read == 0) {
                break  // added
            }
            self.append(buffer, count: read)
        }
        buffer.deallocate(capacity: bufferSize)

        input.close()
    }
}
查看更多
贪生不怕死
3楼-- · 2019-04-10 13:32

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

extension Data {
    init(reading input: InputStream) {
        self.init()
        input.open()

        let bufferSize = 1024
        let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
        while input.hasBytesAvailable {
            let read = input.read(buffer, maxLength: bufferSize)
            self.append(buffer, count: read)
        }
        buffer.deallocate(capacity: bufferSize)

        input.close()
    }
}

Find full code with test here.

查看更多
登录 后发表回答