Lorsque j'utilise la méthode NSOutputStream
's write
func write(_ buffer: UnsafePointer<UInt8>, maxLength length: Int) -> Int
Je ne sais pas comment convertir String
en UnsafePointer<UInt8>
et en longueur
Comment puis-je faire cela rapidement?
Vous devez d'abord convertir la chaîne en données UTF-8
let string = "foo bar"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
puis écrivez-le dans le flux de sortie
let outputStream: NSOutputStream = ... // the stream that you want to write to
let bytesWritten = outputStream.write(UnsafePointer(data.bytes), maxLength: data.length)
La conversion UnsafePointer()
est nécessaire car data.bytes
a le type UnsafePointer<Void>
et non pas UnsafePointer<UInt8>
comme prévu par la méthode write()
Mise à jour pour 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) }
Voici comment le faire dans Swift 3. Courez bien aussi dans Swift 4
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)
}
}
Pour convertir de String
en UnsafeMutablePointer<Int8>
let cString = strdup("Hello") // UnsafeMutablePointer<Int8>
Pour convertir de UnsafeMutablePointer<Int8>
en String
let string = String(cString: cString!) // String
Vous pouvez également laisser Swift le faire pour vous!
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
Une réponse pour les personnes travaillant dans Swift 4 maintenant. Vous ne pouvez plus obtenir d'octets d'un objet de données, vous devez les copier dans un 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)