• 1. ios蓝牙库的基本介绍-CoreBluetooth
  • 2. CoreBluetooth使用详解
  • 3. 相关问题

1. ios蓝牙库的基本介绍-CoreBluetooth

首先熟悉相关名词:Central(中心设备)、Peripheral(外围设备)、advertising(广告)、Services(服务)、Characteristic(特征)

Central:自己的设备(蓝牙)

  • CBCentralManager

Peripheral:搜索到的设备

  • CBPeripheral

advertising:扫描到外围设备时,外围设备所携带的相关信息(有字节长度限制,这
些信息一般都是设备的相关信息)

  • (NSDictionary *)advertisementData

Services:外围设备的服务

  • CBService

Characteristic:外围设备的的特征(可以理解为发现相关服务后,服务下的特征)

  • CBCharacteristic

2. CoreBluetooth使用详解

  • .h 导入头文件,设置代理
#import <CoreBluetooth/CoreBluetooth.h><CBCentralManagerDelegate,CBPeripheralDelegate>
  • 初始化蓝牙
self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
self.manager.delegate = self;
self.BleViewPerArr = [[NSMutableArray alloc]initWithCapacity:1];
  • 开始扫描
-(void)scan{//判断状态开始扫瞄周围设备 第一个参数为空则会扫瞄所有的可连接设备  你可以//指定一个CBUUID对象 从而只扫瞄注册用指定服务的设备//scanForPeripheralsWithServices方法调用完后会调用代理CBCentralManagerDelegate的//- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI方法[self.manager scanForPeripheralsWithServices:nil options:@{ CBCentralManagerScanOptionAllowDuplicatesKey : @NO }];//记录目前是扫描状态_bluetoothState = BluetoothStateScaning;//清空所有外设数组[self.BleViewPerArr removeAllObjects];//如果蓝牙状态未开启,提示开启蓝牙if(_bluetoothFailState==BluetoothFailStateByOff){NSLog(@"%@",@"检查您的蓝牙是否开启后重试");}}
  • CBCentralManagerDelegate方法-蓝牙状态检测
 - (void)centralManagerDidUpdateState:(CBCentralManager *)central
{if (central.state != CBCentralManagerStatePoweredOn) {NSLog(@"fail, state is off.");switch (central.state) {case CBCentralManagerStatePoweredOff:NSLog(@"连接失败了\n请您再检查一下您的手机蓝牙是否开启,\n然后再试一次吧");_bluetoothFailState = BluetoothFailStateByOff;break;case CBCentralManagerStateResetting:_bluetoothFailState=BluetoothFailStateByTimeout;break;case CBCentralManagerStateUnsupported:NSLog(@"检测到您的手机不支持蓝牙4.0\n所以建立不了连接.建议更换您\n的手机再试试。");_bluetoothFailState = BluetoothFailStateByHW;break;case CBCentralManagerStateUnauthorized:NSLog(@"连接失败了\n请您再检查一下您的手机蓝牙是否开启,\n然后再试一次吧");_bluetoothFailState = BluetoothFailStateUnauthorized;break;case CBCentralManagerStateUnknown:_bluetoothFailState = BluetoothFailStateUnKnow;break;default:break;}return;}_bluetoothFailState = BluetoothFailStateUnExit;// ... so start scanning
}
  • CBCentralManagerDelegate方法-发现周围设备
- (void)centralManager:(CBCentralManager *)centraldidDiscoverPeripheral:(CBPeripheral *)peripheraladvertisementData:(NSDictionary *)advertisementDataRSSI:(NSNumber *)RSSI
{if (peripheral == nil||peripheral.identifier == nil/*||peripheral.name == nil*/){return;}NSString *pername=[NSString stringWithFormat:@"%@",peripheral.name];//判断是否存在@"你的设备名"NSRange range=[pername rangeOfString:@"你的设备名"];//如果从搜索到的设备中找到指定设备名,和BleViewPerArr数组没有它的地址//加入BleViewPerArr数组if(range.location!=NSNotFound&&[_BleViewPerArr containsObject:peripheral]==NO){[_BleViewPerArr addObject:peripheral];}_bluetoothFailState = BluetoothFailStateUnExit;_bluetoothState = BluetoothStateScanSuccess;
}

advertisementData即为蓝牙的广播信息,打印信息如下(不同设备携带数据不同,打印查看,或在硬件文档中查看相关key与value)

{kCBAdvDataIsConnectable = 1;kCBAdvDataLocalName = "brand";kCBAdvDataTxPowerLevel = 2;
}
  • 扫描到设备后连接相关设备
//连接设备,调用此方法,peripheral即为存放在数组中的需要连接的设备(根据自己的需要,判断要连接的设备,取出后调用此方芳连接)[_manager connectPeripheral:peripheraloptions:@{CBConnectPeripheralOptionNotifyOnConnectionKey:@YES}];
  • CBCentralManagerDelegate方法-连接上该设备
// 获取当前设备
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{NSLog(@"%@",peripheral);// 设置设备代理[peripheral setDelegate:self];// 大概获取服务和特征[peripheral discoverServices:nil];//或许只获取你的设备蓝牙服务的uuid数组,一个或者多个//[peripheral discoverServices:@[[CBUUID UUIDWithString:@""],[CBUUID UUIDWithString:@""]]];NSLog(@"Peripheral Connected");[_manager stopScan];NSLog(@"Scanning stopped");_bluetoothState=BluetoothStateConnected;}

*注意:连接失败会调用- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError )error

  • CBPeripheralDelegate方法-获取服务
// 获取当前设备服务services- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{if (error) {NSLog(@"Error discovering services: %@", [error localizedDescription]);return;}NSLog(@"所有的servicesUUID%@",peripheral.services);//遍历所有servicefor (CBService *service in peripheral.services){NSLog(@"服务%@",service.UUID);//找到你需要的servicesuuidif ([service.UUID isEqual:[CBUUID UUIDWithString:@"你的设备服务的uuid"]]){//监听它[peripheral discoverCharacteristics:nil forService:service];}}NSLog(@"此时链接的peripheral:%@",peripheral);}
  • CBCentralManagerDelegate方法-获取特征值 :特征值有几种不同的属性(读,写等,可打印查看)

重点:(获取特征值后,可以订阅这个特征的通知,也可写入信息到设备,这两种操作均会返回信息,实现与蓝牙设备的交互,看下面的内容)

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{if (error){NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);return;}NSLog(@"服务:%@",service.UUID);// 特征for (CBCharacteristic *characteristic in service.characteristics){NSLog(@"%@",characteristic.UUID);//发现特征//注意:uuid 分为可读,可写,要区别对待!!!//为蓝牙设备写入信息if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"你的特征uuid"]]){NSLog(@"监听:%@",characteristic);//监听特征//保存characteristic特征值对象//以后发信息也是用这个uuid_characteristic1 = characteristic;[discoveredPeripheral writeValue:d1 forCharacteristic:characteristic1 type:CBCharacteristicWriteWithResponse];}//订阅characteristic特征值的通知if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"你的特征uuid"]]){
//            _characteristic2 = characteristic;
//            [peripheral setNotifyValue:YES forCharacteristic:_characteristic2];
//            NSLog(@"监听:%@",characteristic);//监听特征}}
}
  • CBCentralManagerDelegate方法-读取返回的信息

(上段代码中writeValue:为设备写入信息、setNotifyValue:订阅_characteristic2的通知都会返回信息,返回的信息会在对应的代代理方法中获取:代码中打印的characteristic.value即为返回值)

 - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{if (error){NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);return;}NSLog(@"收到的数据:%@",characteristic.value);}- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{if (error){NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);return;}NSLog(@"收到的数据:%@",characteristic.value);
}

3. 相关问题

  • 获取蓝牙设备的mac地址
    由于框架中不带获取mac地址的相关api,不能像安卓一样通过调用getadress方法获取,ios通过向蓝牙设备写入信息,返回相关的mac地址。具体操作:硬件工程师把mac地址写入指定的特征,ios端调用writeValue:方法传入硬件工程师指定的数据,通过didupdatevalue方法获取到返回的mac地址

  • 实现手机与蓝牙设备的绑定问题
    实现手机与蓝牙设备的绑定原理同获取mac地址:写入相关的手机信息,蓝牙设备存储了手机信息,didupdatevalue方法返回了成功的信息即实现了绑定

ps:有什么问题,活着不明白的可在评论区留言或发送站内信,看到后定会及时回复,毕竟都是一步一步踩坑过来的,后续碰到什么问题,也会及时更新在3. 相关问题

今日分享-ios蓝牙相关推荐

  1. iOS蓝牙原生封装,助力智能硬件开发

    代码地址如下: http://www.demodashi.com/demo/12010.html 人工智能自1956年提出以来,一直默默无闻,近年来人工智能的发展得到重视逐渐发展起步,智能硬件.智能手 ...

  2. iOS蓝牙BLE4.0通信功能

    概述 iOS蓝牙BLE4.0通信功能,最近刚学的苹果,为了实现蓝牙门锁的项目,找了一天学习了下蓝牙的原理,亲手测试了一次蓝牙的通信功能,结果成功了,那么就把我学习的东西分享一下. 详细 代码下载:ht ...

  3. iOS蓝牙学习(一)

    最近在学蓝牙开发,就去网上收集了一些文章看,自己做了一个总结,下面就分享出来. 前提: iOS蓝牙开发使用的API是:Core Bluetooth 正常情况下需要两台真实的蓝牙4.0设备(当然也可以使 ...

  4. signal软件如何退出账号_AppStore今日分享 很贵很强大的视频编辑软件

    最新迅雷iOS捷径分享 AppStore今日分享 可以把iPhone或ipad变成强大的视频编辑工作室 分享软件的账号是大帆网络搜集的不能保证什么时候失效,如果失效请等待下次更新,请下载完毕后迅速退出 ...

  5. IOS蓝牙4.0与读卡器通讯

    IOS学习也一段时间了,该上点干货了.前段时间研究了一下IOS蓝牙通讯相关的东西,把研究的一个成果给大家分享一下. 一 项目背景 简单介绍一下做的东西,设备是一个金融刷卡器,通过蓝牙与iphone手机 ...

  6. 分享iOS游戏/应用的营销及推广技巧(1)

    分享iOS游戏/应用的营销及推广技巧(1) 发布时间:2012-04-10 17:43:41  Tags: 分析API, 制作预告片, 营销及推广技巧, 预开发阶段 作者:Felipe Laso 欢迎 ...

  7. iOS蓝牙开发---CoreBluetooth[BLE 4.0] 初级篇[内附Demo地址]

    一.蓝牙基础知识 (一)常见简称 1.MFI  make for ipad ,iphone, itouch 专们为苹果设备制作的设备,开发使用ExternalAccessory 框架(认证流程貌似挺复 ...

  8. php使用自定义alert,IOS_iOS自定义alertView提示框实例分享,本文实例为大家分享iOS自定义a - phpStudy...

    iOS自定义alertView提示框实例分享 本文实例为大家分享iOS自定义alertView提示框,先上图,弹框的背景色,按钮背景色,提示的消息的字体颜色都可以改变 利用单例实现丰富的自定义接口 / ...

  9. iOS 蓝牙开发 BabyBluetooth蓝牙库介绍

    BabyBluetooth 是一个最简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容iOS和Mac OS X. 特色: 基于原生CoreBluetooth框架封装的轻量级的开源库,可以帮 ...

最新文章

  1. 25个别出心裁的简历设计作品欣赏
  2. 机器不学习:浅显易懂!「高中数学」读懂梯度下降的数学原理
  3. Docker swarm - 使用体验 1+2
  4. Curator实现分布式锁的基本原理-构造函数
  5. Codeforces1142D
  6. Linux 系统下对目录扩容的方法
  7. linux快速mysql5.7_Linux下安装MySQL 5.7
  8. python循环读取文件越来越慢_python读取大文件越来越慢的原因与解决
  9. python3 xpath_【学习笔记】Python3-爬虫-xpath
  10. Stata统计学软件
  11. java面试说话技巧,Java面试题及解答技巧解析介绍
  12. 最新如何将b站视频下载到电脑上不用插件
  13. 前端的三种缓存技术cookie、localStorage、sessionStorage
  14. 不支持16位应用程序,%1和64位电脑不兼容问题
  15. Python戏说NBA:谁是季后赛最强得分手
  16. Python图片批量自动抠图去背景
  17. 从零开始的ZYNQ学习(基于矿卡EBAZ4205)(一)
  18. 【转】ubuntu下为APT设置代理
  19. Proteus8 发生关键仿真错误
  20. 山西省大学计算机专业排名,山西省:排名前14的大学!山西的大学分为5档,前2档最难考!...

热门文章

  1. 实现HTML转PDF 多个PDF合并
  2. 数据分析-spss4.30
  3. 从AdventureWorks学习数据库建模——国际化
  4. WEB开发碰到的问题及经验十八则
  5. 超详细——手把手教你用threejs实现一个酷炫的模型发光扫描效果(一)
  6. .net core 3.1 WebApi项目/Swagger支持二级目录
  7. Nginx代理域名证书替换失效
  8. 台灯照度均匀度多少最好?2022最新护眼灯照度标准值
  9. 小米平板4 android版本,小米平板4/4Plus通刷-LOS-安卓9.0.0-稳定版Stable2.0-来去电归属-农历等-本地化增强适配...
  10. 数据结构—C语言:校园导航系统(最短路径两种算法:深度搜素以及Dijkstra)