iOS--蓝牙通讯/blutooth

1,导入

2,#import <CoreBluetooth/CoreBluetooth.h>

3,协议<CBCentralManagerDelegate,CBPeripheralDelegate>

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

    cm.delegate = self;

 //scan外设

        NSDictionary* scanOptions = [NSDictionary dictionaryWithObject:[NSNumbernumberWithBool:NOforKey: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:[NSNumbernumberWithBool:NOforKey:CBCentralManagerScanOptionAllowDuplicatesKey];

        [cm connectPeripheral:(CBPeripheral *)[_peripheralArrayobjectAtIndex:indexPath.rowoptions: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:writeCharacteristictype:CBCharacteristicWriteWithResponse];

//发送成功调用

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值