Skip to content

Instantly share code, notes, and snippets.

@earltedly
Last active July 23, 2016 09:42
Show Gist options
  • Save earltedly/de85d94f12a9e319c271f69220909d65 to your computer and use it in GitHub Desktop.
Save earltedly/de85d94f12a9e319c271f69220909d65 to your computer and use it in GitHub Desktop.
Read an NSInputStream into a String
extension NSInputStream
{
public func readString(bufferSize: Int = 4096) -> String {
guard let data = NSMutableData(capacity: bufferSize) else { return "" }
let buffer = UnsafeMutablePointer<UInt8>.alloc(bufferSize)
var bytesRead = 0
repeat {
bytesRead = read(buffer, maxLength: bufferSize)
data.appendBytes(buffer, length: bytesRead)
} while bytesRead == bufferSize
let string = String(data: data, encoding: NSUTF8StringEncoding)
return string ?? ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment