Cesare Cesare - 1 year ago 140
iOS Question

How to convert an Int into NSData in Swift?

In Objective-C I use the following code to

  1. Convert an
    variable into
    , a packet of bytes.

    int myScore = 0;
    NSData *packet = [NSData dataWithBytes:&myScore length:sizeof(myScore)];

  2. Use the converted
    variable into a method.

    [match sendDataToAllPlayers:
    packet withDataMode: GKMatchSendDataUnreliable
    error: &error];

I tried converting the Objective-C code into Swift:

var myScore : Int = 0

func sendDataToAllPlayers(packet: Int!,
withDataMode mode: GKMatchSendDataMode,
error: NSErrorPointer) -> Bool {

return true

However, I am not able to convert an
variable into an
and use it an a method. How can I do that?

Rob Rob
Answer Source

To convert Int to NSData:

var score: Int = 1000
let data = NSData(bytes: &score, length: sizeof(Int))

var error: NSError?
if !match.sendDataToAllPlayers(data, withDataMode: .Unreliable, error: &error) {
    println("error sending data: \(error)")

To convert it back:

func match(match: GKMatch!, didReceiveData data: NSData!, fromPlayer playerID: String!) {
    var score: Int = 0
    data.getBytes(&score, length: sizeof(Int))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download