3
我試圖從一個玩家發送以下結構到另一個發送和接收數據:遊戲中心 - 斯威夫特與
struct GamePacket {
var action: String
var pointArray: [CGPoint]
}
我有一個很難搞清楚的GamePacket
轉換爲正確的方式Data
,然後再回來。
下面是代碼我迄今發送包:
func send(packet: GamePacket) {
//convert GamePacket to Data here
let data = Data.init()
var remotePlayerArray = [GKPlayer]()
if let currentPlayer = self.currentPlayer, let match = self.match, let playerArray = self.match?.players {
for player in playerArray {
if player != currentPlayer {
remotePlayerArray.append(player)
}
}
do {
try match.send(data, to: remotePlayerArray, dataMode: GKMatchSendDataMode.reliable)
}
catch {
print("connectionError")
}
}
}
和接收爲代碼:
func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
//convert Data to GamePacket here
}
從寫在ObjectiveC
一些樣品,我設法轉換GamePacket
到Data
使用的東西simmilar以下幾點:
let data = NSData(bytes: &packet, length: MemoryLayout<GamePacket>.size) as Data
但是,我想不出如何將Data
轉換回GamePacket
在接收端,我也沒有肯定這是做了正確的道路。
任何幫助是極大apreciated。謝謝。