swiftfoundationnsinputstream

Reading a NSInputStream produces a -1 bytes available error


I'm trying to do some simple encoding using NSInputStream and NSOutputStream:

import Foundation

let path = "/Users/johni/desktop/a" // holds "123456789abcdef"
var data: NSData = NSData(contentsOfFile: path)
var inp: NSInputStream = NSInputStream(data: data)
println(data.length) // returns 15
println(inp.hasBytesAvailable) // returns false

I'm receiving a -1 from the read method, meaning that it has no bytes available, why does this happen?

I have also have tried initializing the NSInputStream directly with the fileAtPath initializer and got the same error.


Solution

  • You can't use an input stream until you open it.

    inp.open()
    inp.hasBytesAvailable //returns true