两个iOS设备之间的蓝牙连接

12

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

  1. Core Bluetooth框架可以用于与具有蓝牙低功耗(4.0)硬件支持的任何硬件进行通信。
  2. 如果您使用Core Bluetooth技术,则可以忘记Made For iPhone/iPod(MFI)计划。

我有一部iPhone 5、一部iPhone 4S和一部Google Android Nexus 7,并且我确信至少前两者都具有BLE硬件支持。

我的问题是

我在iPhone 4S / iPhone 5上尝试了下面给出的代码,但它未能扫描并找到附近的iPhone 5 / iPhone 4S。我可以确认,两个设备都已打开蓝牙。委托方法didDiscoverPeripheral从未被调用。 可能的原因是什么?我漏掉了什么吗?

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

ViewController.h

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

ViewController.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

我几天后会再次处理BLE的问题...如果你还没有找到解决方案,我会看看能否帮忙。 - Larme
4
我不了解iPhone,但是BLE的工作方式需要一个设备广播,另一个设备才能发现它。因此,您需要两个不同的代码片段... - spamsink
1
@spamsink 嗯...在发布这个问题后,我开始了解它...现在正在研究它...似乎我的蓝牙通信理解是业余的...它看起来并不容易...如果我发现任何东西,我会回复的。 - Krishnabhadra
3个回答

12

正如spamsink所评论的,为了使它们进行通讯,需要有一个设备扮演外设(peripheral),另一个设备扮演中心设备(central)。

苹果提供了一个很好的示例应用程序来实现这一点。此外,还可以查看WWDC 2012会议703 - CoreBluetooth 101和705 - Advanced CoreBluetooth,以了解CoreBluetooth框架的使用方法和示例。

还要注意,设备要想处于外设模式,必须更新到iOS 6.0或更高版本。


示例应用程序和核心蓝牙只能在具备蓝牙4.0的苹果产品上运行。以下是列表链接:http://en.wikipedia.org/wiki/List_of_iOS_devices#Models - Doug Null
看起来这是一个更新的(swift)版本,与上面的“示例应用程序”链接 https://developer.apple.com/documentation/corebluetooth/transferring_data_between_bluetooth_low_energy_devices 相关。 - Steve Ham

3
我的理解是,蓝牙低功耗(BLE)的概念很模糊。正如被接受的答案所指出的,通信需要有一个设备作为中心,另一个设备作为外围。
iOS到iOS和iOS到Mac OS BLE通信的好例子源代码在这里
需要考虑一些重要点:
  1. 在iOS 5.0上,iPhone只能充当中心,因此无法在两个iOS设备之间进行通信。
  2. 在iOS 6.0上,iPhone也可以充当外围。因此,为了进行通信,至少有一个设备必须运行在iOS 6.0(或更高版本)。
  3. 第一个具有BLE硬件的iPhone设备是iPhone 4S。因此,即使iPhone 4可以运行iOS 5,它也无法进行BLE通信。
这就是一些信息。

1
有人尝试过示例源代码(CBPeripheralManager-Demo)吗?它比上面回答中的“示例应用程序”更好吗? - Doug Null

1
如果您在didUpdateState委托中调用scanForPeripherals函数,则它会起作用,因为委托函数无法返回。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接