I want to store JSON text (as String
) in a text file, or rather append each time I have fresh data to add. However, the following code always returns -1 as the return code from output.write()
. I'm doing something wrong but I cannot figure out what:
let fileURL = (try! FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)).first!.appendingPathComponent("data.json")
let json = "..."
let tenGB = 10 * 1000 * 1000 * 1000
if let output = OutputStream(url: fileURL, append: true) {
output.open()
let bytes = output.write(json, maxLength: tenGB)
if bytes < 0 {
print("Failure writing to disk")
} else if bytes == 0 {
print("Failure writing to disk (capacity)")
} else {
print("\(bytes) bytes written to disk")
}
output.close()
} else {
print("Unable to open file")
}
I don't expect the data to be 10 GB at all, more in the kB-MB range, but I thought I'd give it a large value.
The output of streamError
: Error Domain=NSPOSIXErrorDomain Code=22 "Invalid argument" UserInfo={_kCFStreamErrorCodeKey=22, _kCFStreamErrorDomainKey=1}