Last active
July 23, 2016 09:42
-
-
Save earltedly/de85d94f12a9e319c271f69220909d65 to your computer and use it in GitHub Desktop.
Read an NSInputStream into a String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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