When I using NSOutputStream
's write
method
func write(_ buffer: UnsafePointer<UInt8>, maxLength length: Int) -> Int
I don't know how to convert String
to UnsafePointer<UInt8>
and length
How can I do this in swift?
You have to convert the string to UTF-8 data first
let string = "foo bar"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
and then write it to the output stream
let outputStream: NSOutputStream = ... // the stream that you want to write to
let bytesWritten = outputStream.write(UnsafePointer(data.bytes), maxLength: data.length)
The UnsafePointer()
cast is necessary because data.bytes
has the type UnsafePointer<Void>
, and not UnsafePointer<UInt8>
as expected by the write()
method.
Update for Swift 3:
let string = "foo bar"
// Conversion to UTF-8 data (cannot fail):
let data = string.data(using: String.Encoding.utf8)!
// Write to output stream:
let outputStream: NSOutputStream = ... // the stream that you want to write to
let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }
Here is how to do it in Swift 3. Run fine in Swift 4 too
extension String {
func toPointer() -> UnsafePointer<UInt8>? {
guard let data = self.data(using: String.Encoding.utf8) else { return nil }
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count)
let stream = OutputStream(toBuffer: buffer, capacity: data.count)
stream.open()
data.withUnsafeBytes({ (p: UnsafePointer<UInt8>) -> Void in
stream.write(p, maxLength: data.count)
})
stream.close()
return UnsafePointer<UInt8>(buffer)
}
}
To convert from String
to UnsafeMutablePointer<Int8>
let cString = strdup("Hello") // UnsafeMutablePointer<Int8>
To convert from UnsafeMutablePointer<Int8>
to String
let string = String(cString: cString!) // String
Swift 4,
Convert String to NSString, then use NSString's methods.
let text = "Hello"
let pointer: UnsafePointer<Int8>? = NSString(string: text).utf8String
let length = NSString(string: text).length
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