PatrickA
(Patrick A)
1
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?
eskimo
(Quinn “The Eskimo!”)
2
InputStream can be used synchronously or asynchronously. You generally:
Try calling read(_:maxLength:) and see what you get back.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
PatrickA
(Patrick A)
3
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)")
}
eskimo
(Quinn “The Eskimo!”)
4
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
PatrickA
(Patrick A)
5
Thank you, Eskimo, the missing open was indeed the problem. Yes, it's dumb of me.