开发者

GameKit Bluetooth Transfer Problem

开发者 https://www.devze.com 2022-12-31 06:21 出处:网络
I am trying to send a file via Bluetooth using the GameKit framework. The problem I am having though is that I can only send one NSDa开发者_如何学Cta object at a time, but I need to save it on the oth

I am trying to send a file via Bluetooth using the GameKit framework. The problem I am having though is that I can only send one NSDa开发者_如何学Cta object at a time, but I need to save it on the other end. this obviously isn't possible without knowing the filename, but i don't know how to transmit that. I've tried to convert it to a string NSData*data = [NSData dataWithContentsOfFile:urlAddress]; but i can only send one NSData object, not two.

Has anyone come across this problem yet?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消