Reading an InputStream into a Data object
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()
}
}
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.