/* 建立中心设备 扫描外设(Discover Peripheral) 连接外设(Connect Peripheral) 扫描外设中的服务和特征(Discover Services And Charateristics) 利用特征与外设做数据交互(Explore And Interact) 断开连接(Disconnect) */ #import "ViewController.h" #import <coreBluetooth/CoreBluetooth.h> @interface ViewController ()<CBCentralManagerDelegate, CBPeripheralDelegate> @property (nonatomic, strong) CBCentralManager *mgr; /** 发现的外设数组*/ @property (nonatomic, strong) NSMutableArray *peripheralArray; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 1.建立中心设备 // queque:如果说你传空,在主队列 self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil]; // 2.扫描外设 } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; // 最后一步,断开连接 [self.mgr stopScan]; } #pragma CBCentralManagerDelegate /* state: CBManagerStateUnknown = 0, 未知 CBManagerStateResetting, 重置 CBManagerStateUnsupported, 不支持 CBManagerStateUnauthorized, 未经授权 CBManagerStatePoweredOff, 没有启动 CBManagerStatePoweredOn, 开启 */ - (void)centralManagerDidUpdateState:(CBCentralManager *)central { NSLog(@"state = %zd", central.state); // 蓝牙开启 if (central.state == CBManagerStateUnknown) { NSLog(@"未知的蓝牙"); } if (central.state == CBManagerStatePoweredOn) { // 2.扫描外设 [self.mgr scanForPeripheralsWithServices:nil options:nil]; } } /** 3.连接外设(Connect Peripheral) @param peripheral 外设 @param advertisementData 相关的二进制数据 @param RSSI 信号强度 */ - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI { // 1.记录外设,必须要有数组进来行存储 if ([self.peripheralArray containsObject:peripheral]) { [self.peripheralArray addObject:peripheral]; } // 2.隐藏步骤,tableview表格列表(省略了) // 3.连接外围设备 [self.mgr connectPeripheral:peripheral options:nil]; // 4.设置外设的代理 peripheral.delegate = self; } // 连接到外设之后,会调用这个代理方法 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { // 扫描服务 // 传nil代表扫描所有服务 [peripheral discoverServices:nil]; } #pragma CBPeripheralDelegate // 外设扫描里面的服务 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { // 获取外设的服务 for (CBService *service in peripheral.services) { if ([service.UUID.UUIDString isEqualToString:@"123"]) { // uuid一致,那就开始扫描特征 [peripheral discoverCharacteristics:nil forService:service]; } } } // 当发现到特征的时候会调用 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { // for (CBCharacteristic *characteristic in service.characteristics) { if ([characteristic.UUID.UUIDString isEqualToString:@"123456"]) { // [peripheral readValueForDescriptor:<#(nonnull CBDescriptor *)#>]; // [peripheral writeValue:<#(nonnull NSData *)#> forDescriptor:<#(nonnull CBDescriptor *)#>]; } } } - (NSMutableArray *)peripheralArray { if (!_peripheralArray) { _peripheralArray = [NSMutableArray array]; } return _peripheralArray; }