IOS InputStream.read 返回 -1 但 streamError 为 nil

标签 ios swift

我正在尝试从作为 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/

相关文章:

ios - 以编程方式向提醒应用程序添加提醒

ios - 将 Firebase 与适用于 Mac 的 Google 工具箱一起使用时出现 undefined symbol Xcode 错误

ios - Xcode 7.2.1 界面生成器中的自定义字体

ios - 在 Swift 中对私有(private)变量进行单元测试

ios - 将 xcode 中的导航和标签栏 Controller 与 Storyboard 结合起来

ios - Xcode 6 : Error copying template database

swift - 在 Swift 中,我如何访问具有动态类型检查的属性,例如 Obj-C 的 id?

ios - 从 MKPolyline 创建 MKMapView 区域

swift - 如何使用 SwiftSyntax 库递归迭代 Swift Syntax?

ios - SWIFT 3 : Capture photo with AVCapturePhotoOutput (Need another set of eyes to look over code, 为什么这不起作用?)