The solution of this question no longer works with Swift 3.
There is no longer a property bytes
of Data
(formerly NSData
.
Martin R, thank you for your answer. That was a foundation for a complete solution. Here it is:
extension OutputStream {
/// Write String to outputStream
///
/// - parameter string: The string to write.
/// - parameter encoding: The String.Encoding to use when writing the string. This will default to UTF8.
/// - parameter allowLossyConversion: Whether to permit lossy conversion when writing the string.
///
/// - returns: Return total number of bytes written upon success. Return -1 upon failure.
func write(_ string: String, encoding: String.Encoding = String.Encoding.utf8, allowLossyConversion: Bool = true) -> Int {
if let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) {
var bytesRemaining = data.count
var totalBytesWritten = 0
while bytesRemaining > 0 {
let bytesWritten = data.withUnsafeBytes {
self.write(
$0.advanced(by: totalBytesWritten),
maxLength: bytesRemaining
)
}
if bytesWritten < 0 {
// "Can not OutputStream.write(): \(self.streamError?.localizedDescription)"
return -1
} else if bytesWritten == 0 {
// "OutputStream.write() returned 0"
return totalBytesWritten
}
bytesRemaining -= bytesWritten
totalBytesWritten += bytesWritten
}
return totalBytesWritten
}
return -1
}
}