0

我有一张图片,我需要通过蓝牙将其发送到另一台设备。数据是这样的:

NSData *Recording = [NSData dataWithContentsOfFile:myFilePath];
NSString* str = [NSString stringWithFormat:@"%@.ext", button.titleLabel.text];
myDictionary = [[NSMutableDictionary alloc] init];
                    [myDictionary setObject:str forKey:@"fileName"];
                    [myDictionary setObject:@"Recording" forKey:@"fileType"];
                    [myDictionary setObject:Recording forKey:@"FileData"];


NSData* myData = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];

我需要使用以下方法发送 myData 或 myDictionary:

progress = [session sendResourceAtURL:anUrl withName:[imageUrl lastPathComponent] toPeer:peerID withCompletionHandler:^(NSError *error) {
        // Implement this block to know when the sending resource transfer completes and if there is an error.
        if (error) {
            NSLog(@"Send resource to peer [%@] completed with Error [%@]", peerID.displayName, error);
        }
        else {
            // Create an image transcript for this received image resource

        }
    }];

如您所见,我必须在 url 处发送资源,而接收者将在“url”处接收资源,并且我必须从该 url 获取 NSMutabledictionary。基本上我必须发送这个 myDictionary 但我无法弄清楚 url 是如何工作的。谁能解释我必须使用什么网址以及如何创建它?

4

1 回答 1

1

我不确定我是否理解您想要什么,但看起来您只是被困在转移点。

由于您已经将所有内容都转换为 NSData 对象,因此在发送方您需要调用如下内容:

// Assume peerID is correct and data has been prepared
NSError *error;
if ( ![session sendData:data
                toPeers:@[peerID]
               withMode:MCSessionSendDataReliable
                  error:&error] )
    NSLog(@"ERROR - Unable to queue message for delivery - %@",[error localizedDescription]);

在接收方,无论谁是 MCSessionDelegate,都将通过以下方式被调用:

- (void)session:(MCSession *)session
        didReceiveData:(NSData *)data
              fromPeer:(MCPeerID *)peerID;

您可能会在哪里“取消归档” NSData 对象以对其进行处理。

让我也添加一个观察...

从您的示例看来,您正在将文件的全部内容填充到您要归档和发送的字典中。这可能是可行的,但不可取。

更好的方法是将文件作为单独的资源发送。例如,查看发件人的此示例:

// Assume peerID and filePath are both valid and correct 
NSURL *fileURL = [NSURL URLWithString:filePath];
NSString *fileName = [fileURL lastPathComponent];
NSError *error;
[session sendResourceAtURL:resourceURL
                  withName:fileName
                    toPeer:peerID
     withCompletionHandler:^(NSError *error) {
         if (error)
             NSLog(@"Sending to [%@] failed: %@",peerID.displayName, error);
     }];

然后接收者的 MCSessionDelegate 将在传输开始时接收到这两个:

- (void)session:(MCSession *)session 
        didStartReceivingResourceWithName:(NSString *)resourceName
                                 fromPeer:(MCPeerID *)peerID
                             withProgress:(NSProgress *)progress;

...当传输结束时:

- (void)session:(MCSession *)session 
        didFinishReceivingResourceWithName:(NSString *)resourceName
                                  fromPeer:(MCPeerID *)peerID
                                     atURL:(NSURL *)temporaryURL
                                 withError:(NSError *)error;
于 2013-11-20T11:02:53.340 回答