12

我正在尝试iOS 5.0 中引入的Core Bluetooth 框架。根据StackOverflow 本身的许多线程(其中之一):

  1. 核心蓝牙框架可用于与任何 具有蓝牙低功耗 (4.0) 硬件支持的硬件进行通信。
  2. 如果您使用的是核心蓝牙技术,我们可以忘记 Made For iPhone/iPod (MFI) 程序。

我有 iPhone 5、iPhone 4S、Google Android Nexus 7,而且我确信至少前 2 个硬件支持 BLE。

我的问题是

好吧,我在我的 iPhone 4S/iPhone 5 上尝试了下面给出的代码,但它未能扫描并找到附近的 iPhone5/iPhone 4S。我可以确认,两台设备都打开了蓝牙。委托方法didDiscoverPeripheral永远不会被调用。可能是什么原因?我错过了什么吗?

这是我的代码(精简为一个小型测试项目)。

视图控制器.h

@interface ViewController:UIViewController<CBCentralManagerDelegate, CBPeripheralDelegate{
}
@property (strong, nonatomic) CBCentralManager *mCentralManager;
@end

视图控制器.m

@implementation ViewController
@synthesize mCentralManager;

- (void)viewDidLoad{
    [super viewDidLoad];
    mCentralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
    [self scanForPeripherals];
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    NSLog(@"Received periferal :%@",peripheral);
}

- (int) scanForPeripherals {
    if (self.mCentralManager.state != CBCentralManagerStatePoweredOn)
    {
        NSLog(@"self.mCentralManagerState : %d",self.mCentralManager.state);
        return -1;
    }
    //Getting here alright.. bluetooth is powered on.
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
    //Documentation says passind nil as device UUID, scans and finds every peripherals
    [self.mCentralManager scanForPeripheralsWithServices:nil options:options];
    return 0;
}
@end
4

3 回答 3

12

正如 spamsink 所评论的那样,一台设备需要充当外围设备,而一台设备需要充当中心设备才能进行通信。

Apple有一个很棒的示例应用程序可以做到这一点。此外,查看 WWDC 2012 会议 703 - CoreBluetooth 101和 705 - Advanced CoreBluetooth以获得有关 CoreBluetooth 框架使用的很好解释和示例。

另请注意,要使设备处于外围模式,它需要更新到 iOS 6.0 或更高版本。

于 2012-12-13T12:51:18.750 回答
3

好吧,我对蓝牙低功耗 (BLE) 的理解很差。正如公认的答案所指出的,一台设备必须充当中央设备,而另一台设备必须充当外围设备才能进行通信

iOS 到 iOS 和 iOS 到 Mac OS BLE 通信的一个很好的示例源代码在这里

需要考虑的一些要点

  1. 在 iOS 5.0 -> iPhone 只能充当 Central,因此无法在 2 个 iOS 设备之间进行通信。
  2. 在 iOS 6.0 上 -> iPhone 也可以充当外围设备。因此,要进行通信,至少一台设备必须在 iOS 6.0(可能更高版本)上运行。
  3. 第一款添加了 BLE 硬件的 iPhone 设备是 iPhone 4S。因此,即使 iPhone 4 可以运行 iOS 5,也无法在其上进行 BLE 通信。

嗯,有些资料。。

于 2012-12-14T08:21:11.223 回答
1

如果您在 didUpdateState 委托中调用 scanForPeripherals 函数,那么它可以工作,因为委托函数无法返回。

于 2014-12-19T07:15:54.250 回答