iOS开发 蓝牙4.0的各种亲身经历踩过得坑

1.首先建立这个三个参数

@property (nonatomic,strong)CBCentralManager * manager;
@property (nonatomic,strong)CBPeripheral     * peripheral;
@property (nonatomic,strong)CBCharacteristic *writeDataCharacteristic;

2、初始化CBCentralManager

-(CBCentralManager *)manager
{
    if (!_manager )
    {
        _manager  = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) options:nil];

    }
    return _manager;
}

3.开始扫描蓝牙

   [self.manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerRestoredStateScanOptionsKey:@(YES)}];

4.当蓝牙状态改变的时候就会调用这个方法

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStateUnknown:
             //设备不支持的状态
            NSLog(@">>>CBCentralManagerStateUnknown");

            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    ALERTVIEW(@"设备不支持");

                });

            }
            break;
        case CBCentralManagerStateResetting:
            //正在重置状态
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                ALERTVIEW(@"正在重置状态");

            })  ;
        }
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
             //设备不支持的状态
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                ALERTVIEW(@"设备不支持的状态");

            });

        }
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:

            // 设备未授权状态
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                ALERTVIEW(@"设备未授权状态");

            });

        }
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
             //设备关闭状态
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                ALERTVIEW(@"设备关闭状态");

            });

        }
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            //开始扫描周围的外设

            [self.manager scanForPeripheralsWithServices:nil options:@{CBCentralManagerRestoredStateScanOptionsKey:@(YES)}];

            break;
        default:
            break;
    }


}

5.连接外围设备

- (void)connect:(CBPeripheral *)peripheral
{
    // 连接外围设备
    [self.manager connectPeripheral:peripheral options:nil];
}

6.连接玩设备就调用成功的方法,然后开始扫描

//连接到Peripherals-成功 //扫描外设中的服务和特征  连接上外围设备的时候会调用该方法
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);
    //设置的peripheral委托CBPeripheralDelegate
    //@interface ViewController : UIViewController
    [peripheral setDelegate:self];
    //扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    [peripheral discoverServices:nil];

}
//连接到Peripherals-失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
}

7.发现服务和设备的服务设备services

//发现服务
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{

    NSLog(@"Discovered services for %@ ", peripheral.name);
    if (![self.dataSourceArray containsObject:peripheral])
    {
        [self.dataSourceArray addObject:peripheral];
        NSLog(@"%@",peripheral);
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });

    }

}


/**
 *  发现外围设备的服务会来到该方法(扫描到服务之后直接添加peripheral的services)
 */
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{

    NSLog(@"发现外围设备的服务");
    for (CBService *serivce in peripheral.services) {
        NSLog(@"====%@------%@+++++++",serivce.UUID.UUIDString,self.peripheral.identifier);
        if ([serivce.UUID.UUIDString isEqualToString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]) {
            // characteristicUUIDs : 可以指定想要扫描的特征(传nil,扫描所有的特征)
            [peripheral discoverCharacteristics:nil forService:serivce];
        }
    }
}

8.找到了设备的服务然后扫描特征

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"发现外围设备的特征");

    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"====%@------+",characteristic.UUID.UUIDString);

        if ([characteristic.UUID.UUIDString isEqualToString:UUIDSTR_ISSC_TRANS_TX]) {
            // 拿到特征,和外围设备进行交互

            [self notifyCharacteristic:peripheral characteristic:characteristic];
        }
    }
    for (CBCharacteristic *characteristic in service.characteristics) {
        NSLog(@"====%@------+",characteristic.UUID.UUIDString);

        if ([characteristic.UUID.UUIDString isEqualToString:UUIDSTR_ISSC_TRANS_RX]) {
            // 拿到特征,和外围设备进行交互   保存写的特征
            self.writeDataCharacteristic = characteristic;




        }
    }
}

9.最后一步要写上通知这个一定要写上

//设置通知
-(void)notifyCharacteristic:(CBPeripheral *)peripheral
             characteristic:(CBCharacteristic *)characteristic{
    //设置通知,数据通知会进入:didUpdateValueForCharacteristic方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    [self.manager stopScan];

}

//取消通知
-(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral
                   characteristic:(CBCharacteristic *)characteristic{

    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}

10.大功告成只差一步就是写数据

//写数据
-(void)writeCharacteristic:(CBPeripheral *)peripheral
            characteristic:(CBCharacteristic *)characteristic
                     value:(NSData *)value
{
    //只有 characteristic.properties 有write的权限才可以写
    if(characteristic.properties & CBCharacteristicPropertyWrite){
        /*
         最好一个type参数可以为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈
         */
        [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }else{
        NSLog(@"该字段不可写!");
    }
}

11.希望能帮到人,让别人少走点坑。

你可能感兴趣的:(iOS开发 蓝牙4.0的各种亲身经历踩过得坑)