-1

我对 Xcode 很陌生,并且正在努力弄清楚如何使用 coreBluetooth 框架。

我正在尝试连接到 BLE 设备并与之交换数据。我已经经历了几个例子,但我很难理解一切。有谁知道一个非常基本的例子,甚至是关于如何实现所有这些的分步教程?

4

1 回答 1

1

按照此步骤使用蓝牙传输文件。

  1. 添加 GameKit 框架。
  2. 在 .h 文件中

    #import <GameKit/GameKit.h>
    
  3. 在 .h 文件中添加委托

    <GKPeerPickerControllerDelegate,GKSessionDelegate>
    
  4. 在 .h 文件中创建两个对象。

    GKSession *currentSession;
    GKPeerPickerController *picke;
    
  5. 在两侧运行此代码以连接(配对)设备。

    picker = [[GKPeerPickerController alloc] init];
    picker.delegate = self;
    picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
    filePath = fullfilePath;
    [picker show];
    
  6. 连接完成后,将调用以下方法。

    -(void)peerPickerController:(GKPeerPickerController *)pk 
         didConnectPeer:(NSString *)peerID 
         toSession:(GKSession *)session
    
  7. 编写以下代码以在此方法中维护双方的会话。

    currentSession = session;
    session.delegate = self;
    [session setDataReceiveHandler:self withContext:nil];
    picker.delegate = nil;
    [picker dismiss];
    
  8. 此代码将发送文件。

    if(filePath)
    {
        NSData *zipFileData = [NSData dataWithContentsOfFile:filePath];
        if(currentSession)
        {
            [currentSession sendDataToAllPeers:zipFileData 
                   withDataMode:GKSendDataReliable error:nil];
        }
    }
    
  9. 此方法将接收数据。该字段NSData* data具有发送者发送的数据。你可以用它做任何事情。您可以根据需要解析显示或保存。

    - (void) receiveData:(NSData *)data fromPeer:(NSString *)peer 
                 inSession:(GKSession *)session context:(void *)context
    
  10. 以下两种方法有助于维护会话。

     -(void)session:(GKSession *)session peer:(NSString *)peerID 
               didChangeState:(GKPeerConnectionState)state
     {
         @try
         {
             int a = state;
             switch (a)
             {
                 case GKPeerStateConnected:
                     DDLogVerbose(@"connected");
                     break;
                 case GKPeerStateDisconnected:
                     DDLogVerbose(@"disconnected");
                     currentSession = nil;
                     break;
             }
         }@catch (NSException *exception)
         {
             DDLogError(@"Exception : %@", exception);
         }
     }
    
     -(void)session:(GKSession *)session didFailWithError:(NSError *)error
     {
         @try
         {
             DDLogError(@"%@", [error description]);
         }@catch (NSException *exception)
         {
             DDLogError(@"Exception : %@", exception);
         }
     }
    

注意:用 NSLog 替换 DDLog 语句。一切顺利。

于 2013-07-30T05:12:57.317 回答