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?
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.