Problem with Bluetooth GameKit Transfer

I am trying to send a file via Bluetooth using the GameKit framework. The problem I am facing is that I can only send one NSData object at a time, but I need to store it on the other end. this is obviously impossible without knowing the file name, but I do not know how to transfer it. I tried converting it to a string NSData*data = [NSData dataWithContentsOfFile:urlAddress];, but I can only send one NSData object, not two.

Anyone else run into this issue?

+3
source share
1 answer

While working with GameKit for some time, I found that there is a limit of about 90 thousand to “send”, so if you are more than 90k, you will have to break it. Here's how I suggest you figure it out:

1st - send your file name

NSData* fileNameData = [fileNameStr dataUsingEncoding: NSASCIIStringEncoding];
// send 'fileNameData'

2nd - Send the number of pieces you are about to send

NSUInteger fiftyK = 51200;
NSUInteger chunkCount = (((NSUInteger)(srcData.length / fiftyK)) + ((srcData.length % fiftyK) == 0 ) ? 0 : 1))
NSString chunkCountStr = [NSString stringWithFormat:@"%d",chunkCount];
NSData* chunkCountData = [chunkCountStr dataUsingEncoding: NSASCIIStringEncoding];
// send 'chunkCountData'

3rd - Break and submit your NSData object to a set of NSObjects less than 50k each (only for safe size)

NSData *dataToSend;
NSRange range = {0, 0};
for(NSUInteger i=0;i<srcData.length;i+=fiftyK){
  range = {i,fiftyK};
  dataToSend = [srcData subdataWithRange:range];
  //send 'dataToSend'  
}
NSUInteger remainder = (srcData.length % fiftyK);
if (remainder != 0){
  range = {srcData.length - remainder,remainder};
  dataToSend = [srcData subdataWithRange:range];
  //send 'dataToSend'  
}

On the receiving side, you will want to do the following:

1st - Get file name

// Receive data
NSString* fileNameStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]

2nd - Get the number of pieces you are going to receive

// Receive data
NSString* chunkCountStr = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding]
NSUInteger chunkCount = [chunkCount intValue];

3rd - Get chunks of data

NSMutableData data = [[NSMutableData alloc]init];
for (NSUInteger i=0; i<chunkCount;i++){
  // Receive data
  [data appendData:receivedData];
}

If everything worked correctly, now you will have an object fileNameStrcontaining your file name and an object datacontaining the contents of your file.

Hope this helps - AYAL

+13

Source: https://habr.com/ru/post/1746467/


All Articles