1.用xcode 创建一个新的project ,语言选择oc
2.在ViewController 文件中#import"CoreBluetooth/CoreBluetooth.h"头文件
并添加委托方法<CBCentralManagerDelegate,CBPeripheralDelegate>
@property(strong,nonatomic) CBCentralManager *MYCentralManager;
3.在ViewController.m的viewDidLoad方法中加入
self.MYCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
4.在ViewController.m的viewDidLoad方法体中加入两个方法
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state)
{
case CBCentralManagerStateUnknown:
break;
case CBCentralManagerStateUnauthorized:
NSLog(@"模拟器不支持蓝牙测试");
break;
case CBCentralManagerStateUnsupported:
break;
case CBCentralManagerStatePoweredOff:
NSLog(@"蓝牙处于关闭状态");
break;
case CBCentralManagerStatePoweredOn:
NSLog(@"蓝牙已开启");
[self.MYCentralManager scanForPeripheralsWithServices:nil options:nil]; default:
break;
}
}
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary*)advertisementData RSSI:(NSNumber *)RSSI
{
NSLog(@"能发现设备:%@",peripheral.name);
}
5.真机测试
打印结果:
注:蓝牙必须要用真机测试,模拟器是不行的