Reading an InputStream into a Data object

纵然是瞬间 提交于 2020-01-11 03:08:08

问题


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?


回答1:


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

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




回答2:


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


来源:https://stackoverflow.com/questions/42561020/reading-an-inputstream-into-a-data-object

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