iOS--蓝牙通讯/blutooth
iOS--蓝牙通讯/blutooth
少年coder 发表于4年前
iOS--蓝牙通讯/blutooth
  • 发表于 4年前
  • 阅读 1301
  • 收藏 1
  • 点赞 0
  • 评论 0

华为云·免费上云实践>>>   

摘要: 最近做了iOS蓝牙通讯的一个项目,使用blutooth,支持蓝牙ble 4.0

1,导入

2,#import <CoreBluetooth/CoreBluetooth.h>

3,协议<CBCentralManagerDelegate,CBPeripheralDelegate>

4,CBCentralManager *cm = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

    cm.delegate = self;

 //scan外设

        NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];

        [cm scanForPeripheralsWithServices:nil options:scanOptions];


- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI//scan到设备就会调用此方法


//connect设备

NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];

        [cm connectPeripheral:(CBPeripheral *)[_peripheralArray objectAtIndex:indexPath.row] options:scanOptions];


- (void) centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error//连接外设时调用


- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral//当连接上一个外设  CBCentralManager 代理 处理此方法


4,//查询设备服务特征,注意 这块的peripheral 一定得为连接上的设备 后续发送接收数据有用

[peripheral setDelegate:self];

[peripheral discoverServices:nil];

#pragma mark -- CBPeripheralDelegate

//返回的蓝牙服务通知通过代理实现[_peripheral discoverServices:nil];


- (void) peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error

//查询服务所带的特征值[_peripheral discoverCharacteristics:nil forService:myService];

- (void) peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error


5,

//发送数据

[peripheral writeValue:datastr forCharacteristic:writeCharacteristic type:CBCharacteristicWriteWithResponse];

//发送成功调用

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

//处理蓝牙发过来的数据

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error


共有 人打赏支持
粉丝 7
博文 28
码字总数 5105
×
少年coder
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: