[英]Bluetooth connection between 2 iOS devices
我正在尝试 iOS 5.0 中引入的Core Bluetooth 框架。 根据 StackOverflow 本身的许多线程(许多线程之一):
我有一部 iPhone 5、iPhone 4S、Google Android Nexus 7,我确信至少前 2 部有对 BLE 的硬件支持。
好吧,我在我的 iPhone 4S/iPhone 5 上尝试了下面给出的代码,但它无法扫描并找到附近的 iPhone5/iPhone 4S。 我可以确认,两个设备都打开了蓝牙。 委托方法didDiscoverPeripheral
永远不会被调用。 原因可能是什么? 我错过了什么吗?
这是我的代码(精简为一个小型测试项目)。
@interface ViewController:UIViewController<CBCentralManagerDelegate, CBPeripheralDelegate{
}
@property (strong, nonatomic) CBCentralManager *mCentralManager;
@end
@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
正如 spamsink 所评论的那样,一台设备需要充当外围设备,另一台设备需要充当中心以便它们进行通信。
Apple 有一个很棒的示例应用程序可以做到这一点。 此外,请查看 WWDC 2012 会议 703 - CoreBluetooth 101和 705 - Advanced CoreBluetooth以获得有关 CoreBluetooth 框架使用的精彩解释和示例。
另请注意,要使设备处于外围模式,则需要将其更新到 iOS 6.0 或更高版本。
好吧,我对低功耗蓝牙 (BLE) 的一般理解很差。 正如公认的答案所指出的那样,一台设备必须充当中央设备,而另一台设备必须充当外围设备才能进行通信。
iOS 到 iOS 和 iOS 到 Mac OS BLE 通信的一个很好的示例源代码在这里。
需要考虑的一些要点
那么一些信息..
如果您在 didUpdateState 委托中调用 scanForPeripherals 函数,那么它会起作用,因为委托函数无法返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.