我正在尝试使用iOS 5.0中引入的Core Bluetooth框架。根据StackOverflow上的许多线程(其中之一):
- Core Bluetooth框架可以用于与具有蓝牙低功耗(4.0)硬件支持的任何硬件进行通信。
- 如果您使用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