Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created October 17, 2022 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tgnivekucn/0532e10c963345f539db532164404f10 to your computer and use it in GitHub Desktop.
Save tgnivekucn/0532e10c963345f539db532164404f10 to your computer and use it in GitHub Desktop.
Buffered writing to a file with Swift OutputStreamType and GCD i/o channel (Original version in Objective-C: https://gist.github.com/algal/54467df650c875827f2b)
// Ref:
// https://gist.github.com/algal/54467df650c875827f2b
// https://developer.apple.com/documentation/dispatch/dispatchio/2892309-init
class FileOutputStream: OutputStream {
private var filepath: URL!
private var channel: DispatchIO!
// Initialized an output stream that writes to `filepath`.
// - requires: `filepath` must be a file path URL, for a file that can be created.
init?(filepath: URL) {
super.init(url: filepath, append: true)
self.filepath = filepath
if let cpath = filepath.path.cString(using: .utf8) {
let outputflag: Int32 = O_CREAT | O_WRONLY
let mode: mode_t = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
self.channel = DispatchIO(type: .stream,
path: cpath,
oflag: outputflag,
mode: mode,
queue: .global(qos: .background)) { errorCode in
if errorCode != 0 {
print("FileOutputStream: error creating io channel")
}
}
} else {
self.channel = nil
return nil
}
}
// Initializes output stream to write to `filename` in the user's Documents directory.
convenience init?(filename: String) {
if let pathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(filename) {
self.init(filepath: pathURL)
} else {
return nil
}
}
func write(string: String) {
if let dataString = string.data(using: .utf8) {
let dispatchData = dataString.withUnsafeBytes { DispatchData(bytes: $0)}
channel.write(offset: 0, data: dispatchData, queue: .global(qos: .background)) { done, data, errorCode in
if errorCode != 0 {
print("FileOutputStream: error creating io channel")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment