GameKit Bluetooth Transfer Problem

后端 未结 1 1488
渐次进展
渐次进展 2020-12-28 11:19

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 NSData object at a time, but I need to save

相关标签:
1条回答
  • 2020-12-28 11:47

    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 讨论(0)
提交回复
热议问题