24893

Extract struct from NSData in Swift

Question:

I'm making Game Center game. I send a data packet containing a struct MovePacket like this:

var packet = MovePacket(packetID: 1, move: myMove) let dataPacket = NSData(bytes: &packet, length: sizeof(MovePacket)) currentMatch!.sendDataToAllPlayers(dataPacket, withDataMode: GKMatchSendDataMode.Reliable, error: nil)

This works like in Objective-C, but I don't understand how to decode the received NSData back to my struct MovePacket. This is one of my tries:

func match(match: GKMatch!, didReceiveData data: NSData!, fromRemotePlayer player: GKPlayer!) { var packet : MovePacket data.getBytes(&packet, length: sizeof(MovePacket)) // getting error here: Address of variable 'packet' taken before it is initialized println(packet) //Variable 'packet' used before being initialized }

Answer1:

Assuming you meant “decode it back from <strong>NSData</strong>”:

func match(match: GKMatch!, didReceiveData data: NSData!, fromRemotePlayer player: GKPlayer!) { if data.length == sizeof(MovePacket) { let packet = UnsafePointer<MovePacket>(data.bytes).memory println(packet) } else { // error: data size is incorrect } }

Recommend

  • Test if an exception is caught with Junit
  • oracle.jdbc.ReadTimeout and Socket read timed out
  • UITableView delegates not getting called after NSURL delegates
  • How to build message from tcp segments
  • XML SAX Parser not working - NullPointerException [closed]
  • How create UIImage from bytes?
  • Error Domain=NSCocoaErrorDomain Code=3840 “Invalid value around character 0.” UserInfo={NSDebugDescr
  • Assignment of Allocatables of Different Shapes in Fortran [duplicate]
  • “[CALayer release]: message sent to deallocated instance” when dismissing modal view controller
  • OSStatus error -50 (invalid parameters) AudioQueueNewInput recording audio on iOS
  • Why can't I extract data from media file using AVURLAsset in a Playground?
  • iOS 9 custom transition - animationControllerForDismissedController not called
  • UIScrollView setContentOffset: animated: not working
  • Why does Apple use assign rather than weak to store a delegate?
  • How to work with AMMediaType for video filters
  • Should I be afraid to use UDP to make a client/server broadcast talk?
  • Should a web service response include empty values?
  • How to unpack 32bit integer packed in a QByteArray?
  • How to access profile picture with Facebook API in Swift 3?
  • UIAlertController button function not working
  • How to remove a SwiftyJSON element?
  • Connect .sks to skscene.h
  • copying resource to sdcard gives a damaged file in android
  • Row Count Is Returning the incorrect number using RaptureXML
  • Spark fat jar to run multiple versions on YARN
  • Why is the size of this struct 32?
  • AES padding and writing the ciphertext to a disk file
  • Obtain ObjectIdHex value from mgo query
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Circular dependency while pushing http interceptor
  • retrieve vertices with no linked edge in arangodb
  • Linker errors when using intrinsic function via function pointer
  • NSLayoutConstraint that would pin a view to the bottom edge of a superview
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Change div Background jquery
  • Linking SubReports Without LinkChild/LinkMaster
  • apache spark aggregate function using min value
  • Bitwise OR returns boolean when one of operands is nil
  • Is it possible to post an object from jquery to bottle.py?
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass