我正在尝试从作为 Assets 包含在 Swift 项目中的文件中读取 4 个字节。下面代码中的流是一个 InputStream,创建为:
let part = fileName.components(separatedBy: ".")
let path = Bundle.main.path(forResource: part[0], ofType: part[1])
let stream = InputStream.init(fileAtPath: path!)
但是,出于某种原因,InputStream.read 返回 -1。文档指出,当返回 -1 时,更多信息将出现在 streamError 字段中,但调试器将该字段显示为 nil。
var val = [UInt8](repeating: 0, count: 4)
let bytesRead = stream.read(&val, maxLength: 4)
let err = stream.streamError
let desc = err.debugDescription
文件有 100kb 长,所以它不应该在流的末尾。
最佳答案
你必须open()
在您可以从中读取或写入之前的流:
let stream = InputStream(fileAtPath: path!)
stream.open()
关于IOS InputStream.read 返回 -1 但 streamError 为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43569157/