游戏开始后传输 Interger GameKit

Transferring Interger once a game has started GameKit

我已成功使用 Apple 文档通过 Game Center 连接两个玩家并开始游戏。然而,几天来我一直在努力让应用程序在两个玩家之间发送数据。

我只需要在两个播放器之间发送一个整数,但甚至无法将文档代码发送到 运行,即使在创建结构等之后也是如此。我看过的示例已经过时了,或者我可以'让他们建造。

func sendPosition() {

let messageToSend = 123

//what do I need to do messageToSend to send it?

    do {
        try match.sendData(toAllPlayers: packet, with: .unreliable)
    } catch {
    }

    if error != nil {

        // Handle the error.
    }

}

    func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
       //What do I need to do to receive the data?

       }

如果有人可以帮助我在 Swift 5+ 中试验一些工作代码,我将不胜感激。

经过一些阅读和播放,我的原始代码似乎可以工作!!!如果对其他人有帮助:

发送:

@IBAction func sendDataBtn(_ sender: Any) {
    print("sending data")
    let dataString = "Hello, World!"
    let dataToSend = dataString.data(using: .utf8)
    do {
    try myMatch.sendData(toAllPlayers: dataToSend!, with: .reliable)
    } catch {
        print(error.localizedDescription)
    }
}

接收:

func match(_ match: GKMatch, didReceive data: Data, fromRemotePlayer player: GKPlayer) {
    print("Data Received")
    let receivedData = String(data: data, encoding: .utf8)
    messageLbl.text = receivedData
}

我创建了一个 'container' 来发送数据,这样我就可以一次性添加指令和需要完成的操作。例如;

    var type:String = "jump"
    var data:CGPoint = CGPoint(x:10,y:10)
    
    let container:[Any] = [type, data]

    
do {
      let dataToSend = try NSKeyedArchiver.archivedData(withRootObject: container, requiringSecureCoding: true)
        try match.sendData(toAllPlayers: packet, with: .unreliable)
    } catch {
    }

    if error != nil {

        // Handle the error.
    }