1、导入CoreBlueTooth框架,遵守协议,建立管理者
#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController ()<CBCentralManagerDelegate , CBPeripheralDelegate>
//建立中央管理者
@property (nonatomic,strong)CBCentralManager *manager;
//存储搜索到的设备
@property (nonatomic,strong)NSMutableArray *array;
@end
2、懒加载初始化管理者和储存数组
-(CBCentralManager *)manager{
if (_manager == nil) {
_manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
}
return _manager;
}
-(NSMutableArray *)array{
if (_array == nil) {
_array = [[NSMutableArray alloc]init];
}
return _array;
}
3、创建按钮,点击按钮搜索设备
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"搜索设备" style:UIBarButtonItemStylePlain target:self action:@selector(Button:)];
self.navigationItem.rightBarButtonItem = rightButton;
}
- (void)Button:(UIBarButtonItem *)sender{
// serviceUUIDs 将想要搜索的设备的UUID传入 nil就是搜索所有的
[self.manager scanForPeripheralsWithServices:nil options:nil];
}
4、CBCentrancelManagerd的代理方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
// 状态发生改变的时候滴啊用 (开 关)
NSLog(@"当前蓝牙的状态:%ld",(long)central.state);
}
// 发现外围设备的时候调用 advertisementData 外围设备发出的信号 RSSI 信号强度
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
// 将所有的设备添加到数组中,用tabelView展示
if (![self.array containsObject:peripheral]) {
[self.array addObject:peripheral];
}
NSLog(@"设备的个数:%ld",self.array.count);
}
// 链接外围设备调用方法 peripheral 链接上的设备
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
// 扫描所有的服务 也可以通过UUID 链接到特定的服务
[peripheral discoverServices:nil];
// 设置外围设备的代理
peripheral.delegate = self;
}
5、CBPeripheral的代理方法(外围设备的代理方法)
//发现外围设备的服务 (扫描到服务后直接添加到Perrpheral的数组中)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
for (CBService *serive in peripheral.services) {
if ([serive.UUID.UUIDString isEqualToString:@"你需要搜索的服务UUID"]) {
// characteristicUUIDs:可以指定想要的扫描的特征
[peripheral discoverCharacteristics:nil forService:serive];
}
}
}
//当扫描到某一个服务的特征的时候调用
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID.UUIDString isEqualToString:@"扫描你需要的特征UUID"]) {
// 拿到特征和外围设备进行交互;
}
}
}
6、链接、断开设备调用方法
#pragma mark - 链接设备
-(void)connct:(CBPeripheral *)peripheral{
// 链接外围设备
[self.manager connectPeripheral:peripheral options:nil];
}
#pragma mark - 断开连接
- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral{
NSLog(@"断开连接");
}