Search code examples
iosswiftnsdata

How to know what type is the data sent?


I've got this function where I retrive some datas sent during some functions:

@available(iOS 9.0, *)
func match(_ match: GKMatch, didReceive data: Data, forRecipient recipient: GKPlayer, fromRemotePlayer player: GKPlayer) {
    print("RECEIVED DATA 9.0")
        receiveData(turnLog: data, player: player)
        receiveDataAction(movment: data, player: player)
        receiveDataActionTop(movmentTop: data, player: player)
}

But obviously every func that I call is related to a specific data. How can I know the "type" of data that I'm receiving to create an if-else statement?

I send this data like this:

let encoder = JSONEncoder()
let dataMovment = try! encoder.encode(SKActionDescriptor(x: 450, duration: 0.25, x2: 1050, duration2: 0.5))
try match?.sendData(toAllPlayers: dataMovment, with: GKMatchSendDataMode.reliable)

Solution

  • That entirely depends on what kind of data you're sending through. It's up to you to set up a system where the receiver can figure out what data it's dealing with.

    Generally, there are 2 ways.

    1. Either the schema (the "layout" of the data) is communicated as part of the data. e.g. JSON, where the [ ]/{ } communicate the structure of the fields. When you get a chunk of JSON, you don't know how long the first object in array goes on for. It starts at the {, and goes on until the matching }. The JSON itself encodes a description of its own layout.

    2. The schema is protocol-defined, and isn't transmitted. A receiver that correctly implements that protocol will expect the data coming into it to match the constraints defined in the protocol. For example a UDP packet, which is just "raw" data, whose schema isn't transmitted, but rather, is defined by the protocol:

      • The first 2 bytes encode the source port
      • The second 2 bytes encode the destination port
      • The next 2 bytes encode the payload size
      • The next 2 bytes encode the checksum for the packet
      • The next n bytes constitute the payload.

      None of this structural information is self-described by the packet. Rather, it's defined by the UDP protocol, and any sender/receiver that "plays nice" is expected to follow that schema.