将 InputStream 读入 Data 对象 [英] Reading an InputStream into a Data object
本文介绍了将 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屋!
查看全文