蓝牙

通过iOS设备的蓝牙与外围设备交互

  • 1.需要以下几个类
#import <CoreBluetooth/CoreBluetooth.h>
#import <CoreBluetooth/CBService.h>
#import <CoreBluetooth/CBCharacteristic.h>
  • 2.遵循CBCentralManagerDelegate, CBPeripheralDelegate这两个协议
  • 3.初始化蓝牙管理者 CBCentralManager *centralManager;,通过管理者来做相应的蓝牙操作
- (void)initManager{
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

}
  • 4.查看蓝牙的连接状态
通过 _centralManager.state 可以拿到  一共有五种状态
 0:蓝牙状态未知,
1:蓝蓝牙正在重启,
2:设备不支持蓝牙,
3:蓝牙未授权,
4:蓝牙关闭,
5:蓝牙开启,"
  • 5.扫描蓝牙设备
    • 根据已知的 蓝牙设备的服务(CBUUID *)UUID 或者蓝牙名称(NSString *)BlueToothName或者前缀名来搜索设备
    [_centralManager scanForPeripheralsWithServices:UUID options:nil];
  • 6.停止扫描

[_centralManager stopScan];

  + 7.连接设备
    -  1.根据设备的唯一标识UUID(相当于mac地址的uuid) 来连接设备:把扫描到的设备放到一个数组中,遍历所有扫描设备的UUID (相当于mac地址的uuid),拿到要连接的设备 。调用连接方法
[_centralManager connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
  + 8.断开连接

if(peripheral.state == CBPeripheralStateConnected) {
[_centralManager cancelPeripheralConnection:peripheral];
}

  + 9.  根据服务的UUID,获得iOS已经连接的设备

NSArray *retrivedPer = [_centralManager retrieveConnectedPeripheralsWithServices:@[[CBUUID UUIDWithString:UUID]]];

  + 10.实现CBPeripheralDelegate的代理
      - 1.根据服务拿到读写特征值
          ```
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error;
            ```
     - 2.用写的特征值给设备写值 此类命令有返回数据到iOS端,用读的特征值 通知   外围设备,此命令写入外围设备无回应
              - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
    - 3.在下面代理可拿到外围设备返给ios设备的值
               - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error;
                  ```

文章参考

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 蓝牙简介 蓝牙( Bluetooth® ):是一种无线技术标准,可实现固定设备、移动设备和楼宇个人域网之间的短距离...
    Chefil阅读 2,237评论 2赞 19
  • 随着智能家具、智能穿戴等的兴起,蓝牙开发应用越来越广泛,有关蓝牙方面的问题,今天就给大家进行详细的讲解,想要了解蓝...
    知易行难880721阅读 695评论 0赞 0
  • 微风推着水动 一条小鱼害羞的遁入水中 泛起我眼睛的涟漪 海水住在眼睛里 时不时的涌动 击碎了我的心 渐渐渐渐 我的...
    siee阅读 273评论 0赞 1
  • 一饮长剑凉如霜 抬头明月皎似琅 谁歌笙箫苦短若 谁叹锦弦生涩鸣 年少执剑荡平心中阔 时光荏苒飘过谁承诺 挥毫笔墨只...
    怡宝鱼阅读 333评论 0赞 2
  • 看过临产前几天还在工作的孕妇,加班到深夜仍然咬牙坚持;看过顶着零下三十度的严寒还在卖糖葫芦的小伙,冻得浑身颤抖仍然...
    慕新阳阅读 1,090评论 13赞 20

友情链接更多精彩内容