How do I send data from a GKPlayer to another in a match?

坚强是说给别人听的谎言 提交于 2020-01-07 06:13:02

问题


I would like to send NSData from a GKPlayer to another in a match. Therefore, the method sendDataToAllPlayers(_:withDataMode:error:) would be the most ideal.

func sendDataToAllPlayers(data: Int,
    withDataMode Reliable: GKMatchSendDataMode,
    error: NSErrorPointer) -> Bool {

    return true
}

Though, how can I use the method above to send an Int variable?

var score:Int = 0

回答1:


This version for encapsulating an Int (or other type) into or extracting it fromNSData should work even between devices with different byte orders:

// at sender before sending data
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.encodeInteger(score, forKey: "score")
archiver.finishEncoding()

// at receiver after receiving data
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
let score = unarchiver.decodeIntegerForKey("score")
unarchiver.finishDecoding()



回答2:


extension Int {
    var data: NSData {
        var source = self
        return NSData(bytes: &source, length: sizeof(Int))
    }
}
extension Double {
    var data: NSData {
        var source = self
        return NSData(bytes: &source, length: sizeof(Double))
    }
}
extension NSData {
    var integerValue:Int {
        var result = 0
        getBytes(&result, length: sizeof(Int))
        return result
    }
    var doubleValue:Double {
        var result:Double = 0
        getBytes(&result, length: sizeof(Double))
        return result
    }
}

let myIntegerData = 123.data                 // _NSInlineData
let backToInt = myIntegerData.integerValue   // 123

let myDoubleData = 123.456789.data           // _NSInlineData
let backToDouble = myDoubleData.doubleValue  // 123.456789


来源:https://stackoverflow.com/questions/28662770/how-do-i-send-data-from-a-gkplayer-to-another-in-a-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!