When I using NSOutputStream
\'s write
method
func write(_ buffer: UnsafePointer, maxLength length: Int) -> Int
You can also let Swift do it for you!
import Foundation
// Example function:
func printUTF8Vals(_ ptr: UnsafePointer<UInt8>, _ len: Int) {
for i in 0..<len {
print(ptr[i])
}
}
// Call it:
let str = "Hello"
printUTF8Vals(str, str.lengthOfBytes(using: String.Encoding.utf8))
// Prints:
// 72
// 101
// 108
// 108
// 111
An answer for people working in Swift 4 now. You can no longer get bytes from a Data object, you have to copy them into an UnsafeMutablePointer
let helloWorld = "Hello World!"
let data = helloWorld.data(using: String.Encoding.utf8, allowLossyConversion: false)!
var dataMutablePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count)
//Copies the bytes to the Mutable Pointer
data.copyBytes(to: dataMutablePointer, count: data.count)
//Cast to regular UnsafePointer
let dataPointer = UnsafePointer<UInt8>(dataMutablePointer)
//Your stream
oStream.write(dataPointer, maxLength: data.count)
By far the easiest way (in Swift 5):
let s = "hello, world"
let pointer = UnsafePointer(Array(s.utf8CString))
Not sure how backwards compatible this is.