I need to transmit an integer through GameKit using sendDataToAllPeers:withDataMode:error:
but I don't know how to convert my NSNumber to NSData in order to send. I currently have:
NSNumber *indexNum = [NSNumber numberWithInt:index];
[gkSession sendDataToAllPeers:indexNum withDataMode:GKSendDataReliable error:nil];
but obviously the indexNum needs to be converted to NSData before I can send it. Does anyone know how to do this please?
Thanks!
I would not recommend NSKeyedArchiver
for such a simple task, because it adds PLIST overhead on top of it and class versioning.
Pack:
NSUInteger index = <some number>;
NSData *payload = [NSData dataWithBytes:&index length:sizeof(index)];
Send:
[session sendDataToAllPeers:payload withDataMode:GKSendDataReliable error:nil];
Unpack (in the GKSession receive handler):
NSUInteger index;
[payload getBytes:&index length:sizeof(index)];
var i = 123
let data = NSData(bytes: &i, length: sizeof(i.dynamicType))
var i2 = 0
data.getBytes(&i2, length: sizeof(i2.dynamicType))
print(i2) // "123"
To store it:
NSData *numberAsData = [NSKeyedArchiver archivedDataWithRootObject:indexNum];
To convert it back to NSNumber:
NSNumber *indexNum = [NSKeyedUnarchiver unarchiveObjectWithData:numberAsData];
Why not send the integer directly like this:
NSData * indexData = [NSData dataWithBytes:&index length:sizeof(index)];
[gkSession sendDataToAllPeers:indexData withDataMode:GKSendDataReliable error:nil];
有关如何发送不同有效负载的更详细示例,您可以查看 XCode 文档中包含的 GKRocket 示例。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.