swiftnsstreamnsoutputstream

Convert Int to UnsafePointer<UInt8>


I'm creating a TCP client in swift for an app on iOS device. I'm using NSOuputStream to send data on the server. Our protocol is JSON type and we have to send first the length of the json (unsigned Int 32 bits) and then the JSON content (as UTF8 string).

Every thing work fine, except that I cannot find how to write my Int using write(_:maxLength:) function of NSOutputStream..

To convert my JSON String into UnsafePointer<UInt8> I use the following

//var json: String
let encodedData = [UInt8](json.utf8)
let result = outputStream?.write(encodedData, maxLength: encodedData.count)

Does someone know how to do it for an Int ?

Thanks for your help !


Solution

  • You should be able to do something like this:

    var int = 100
    
    let result = withUnsafePointer(&int) {
        outputStream?.write(UnsafePointer($0), maxLength: sizeof(Int))
    }
    

    EDIT: To read your Int you can do

    func getInt(ptr: UnsafePointer<UInt8>) -> Int {
        return UnsafePointer(ptr).memory
    }