我想送一些NSData过Bluetooth通过GameKit.
虽然我已经GameKit设置好并且能够发送小消息,但我现在想要扩展并发送整个文件.
我一直在读你必须将大文件分成数据包然后单独发送它们.
所以我决定创建一个struct以便在另一端收到数据包时更容易解码数据包:
typedef struct {
const char *fileName;
NSData *contents;
int fileType;
int packetnumber;
int totalpackets;
} file_packet;
Run Code Online (Sandbox Code Playgroud)
但是,对于小文件(8KB或更少),我认为一个数据包就足够了.
所以对于一个数据包,我想我可以创建一个file_packet,设置它的属性,并通过-sendDataToAllPeers:withDataMode发送它:error:
NSData *fileData;
file_packet *packet = (file_packet *)malloc(sizeof(file_packet));
packet->fileName = [filename cStringUsingEncoding:NSASCIIStringEncoding];
packet->contents = [NSData dataWithContentsOfFile:selectedFilePath];
packet->packetnumber = 1;
packet->totalpackets = 1;
packet->fileType = 56; //txt document
fileData = [NSData dataWithBytes:(const void *)packet length:sizeof(file_packet)];
free(packet);
NSError *error = nil;
[self.connectionSession sendDataToAllPeers:fileData withDataMode:GKSendDataReliable error:&error];
if (error) {
NSLog(@"An error occurred: …Run Code Online (Sandbox Code Playgroud)