Is it possible to read a file saved in sandbox with InputStream?

I write a file in this way:

let text = " Fußgänger"

if let dir = FileManager.default.urls(for: .documentDirectory,
                                      in: .userDomainMask).first {

let fileUrl =  dir.appendingPathComponent("pietons.txt")

do {
       try text.write(to: fileUrl, atomically: false , encoding: .utf8)
  }
catch {
      print ("error: \(error).")
  }



Then, just after, I'm trying to read it using InputStream 


guard let iStr = InputStream(url: fileUrl) else {

throw MyError.runTimeError("Could not open \(fileUrl)")
 
     }
 
 guard iStr.hasBytesAvailable else {
 
 throw MyError.runTimeError("No data available for \(fileUrl)")
 
     }

I am able to open the InputStream (InputStream(url: fileUrl) does not error) But there seems to be no bytes available... while I do see these bytes if I use

String(contentsOf: fileurl, encoding: .utf8)

Did I make a mistake? How could inputStream read the file I created with the write() above?

InputStream can be used synchronously or asynchronously. You generally:

  • Work with file streams synchronously

  • Don’t use hasBytesAvailable when using it synchronously

Try calling read(_:maxLength:) and see what you get back.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

I had tried that and got -1.

let buff = UnsafeMutablePointer<UInt8>.allocate(capacity: 8)
let readLen = iStr.read(buff, maxLength: 5 )
print("read \(readLen) bytes ")
guard iStr.hasBytesAvailable else {
   throw MyError.runTimeError("No data available for \(fileUrl)")
}

Three things:

  • The result of -1 indicates an error. You can get details on the error via the streamError property. What does it return?

  • You don’t need to manually allocate memory for the read. Rather, try this:

      var buf = [UInt8](repeating: 0, count: 8)
      let readLen = iStr.read(&buf, maxLength: buf.count)
    

    .

  • You don’t seem to be calling open on the stream. Did you just elide that for the sake of this post? If not, that’s probably the immediate cause of your problem.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

Thank you, Eskimo, the missing open was indeed the problem. Yes, it's dumb of me.