GameKit Bluetooth Transfer Problem

跟風遠走 提交于 2019-11-30 02:32:07

Working with the GameKit for a while I've found that there is a limit of about 90k per 'send' so if you're file is larger then 90k you'll have to break it up. Here is how I would suggest you break things up:

1st - Send the name of your file

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

2nd - Send the number of chunks your going 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 up and send your NSData object into a set of NSObjects of less then 50k each (just to be on the 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'll want to do the following:

1st - Receive the file name

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

2nd - Receive the number of chunks you are about to receive

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

3rd - Receive the chunks of data

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

If everything has worked right you will now have a fileNameStr object containing your file name and a data object containing the contents of your file.

Hope this helps - AYAL

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