I have the method which has to print the username when the user connected but the error withUnsafeBytes is deprecated: use withUnsafeBytes(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R instead pops up.
method:
func joinChat(username: String) {
let data = "iam:\(username)".data(using: .ascii)!
self.username = username
_ = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) } //deprecated
}
Somebody know how to solve it?
It looks like withUnsafeBytes
relies on assumingMemoryBound(to:)
on Swift 5, there are some threads regarding it, e.g: https://forums.swift.org/t/how-to-use-data-withunsafebytes-in-a-well-defined-manner/12811
To silence that error, you could:
func joinChat(username: String) {
let data = "iam:\(username)".data(using: .ascii)!
self.username = username
_ = data.withUnsafeBytes { dataBytes in
let buffer: UnsafePointer<UInt8> = dataBytes.baseAddress!.assumingMemoryBound(to: UInt8.self)
OutputStream(toMemory: ()).write(buffer, maxLength: dataBytes.count)
}
}
But it seems unsafe and confusing. It would be better to go with @OOper solution I think.
You may find some solutions on how to use new Data.withUnsafeBytes
, but if you are using it just for calling OutputStream.write
, you have another option:
func joinChat(username: String) {
let str = "iam:\(username)"
self.username = username
outputStream.write(str, maxLength: str.utf8.count)
}
This code does not have a feature that crashes your app when username
contains non-ascii characters, but other than that, it would work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With