Hi,
I have a network stream which I want to send data. I had an original few lines (copied from an example) which seemed to do the job, but gave the Xcode warning. After a couple of days I'm seemingly going round in circles, and down the deadend of empty documentation ('No overview available' on withUnsafeBytes).
Is my refactored verison correct? Both versions of 'write' work, as in the remote endpoint gets the data. But..
1. in the second version, withUnsafeBytes should be a throwing function so I presume that I'm not actually using the correct method?
2. in the first version the Int is returned by .write(), but this was never returned in the second version. What am I not understanding?
func sendMessage(msg: String) {
if var data = msg.data(using: .utf8) {
// original
// WARNING: 'withUnsafeBytes' is deprecated: use `withUnsafeBytes(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead
let dataSent = data.withUnsafeBytes({
self.outputStream?.write($0, maxLength: data.count)
})
print("dataSent: \(String(describing: dataSent))")
// refactored
// pointer type chicanery, and method signatures from the Apple docs:
// Data: func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType
// OutputStream: func write(_ buffer: UnsafePointer, maxLength len: Int) -> Int
data.withUnsafeBytes({
let unsafeBufferPtr = $0.bindMemory(to: UInt8.self)
if let unsafePtr = unsafeBufferPtr.baseAddress {
let dataSent2 = self.outputStream?.write(unsafePtr, maxLength: $0.count)
print("dataSent2: \(String(describing: dataSent2))")
}
})
}
}
thanks,