蓝牙设备MFI认证和Core bluetooth 蓝牙耳机关系是怎么样的

CoreBluetooth- iOS蓝牙开发 - 简书
CoreBluetooth- iOS蓝牙开发
一、蓝牙基础知识
(一)常见简称
make for ipad ,iphone, itouch 专们为苹果设备制作的设备,开发使用ExternalAccessory 框架(认证流程貌似挺复杂的,而且对公司的资质要求较高),详见:
BLE buletouch low energy,蓝牙4.0设备因为低耗电,所以也叫做BLE,开发使用CoreBluetooth 框架
(二)两种模式
CBCentralMannager 中心模式 :以手机(app)作为中心,连接其他外设的场景(主要写此种该模式的应用方法,因为我只会这种模式的)
CBPeripheralManager 外设模式:使用手机作为外设连接其他中心设备操作的场景
(三)CBPeripheral 、CBService、CBCharacteristic
三者关系:
CoreBluetooth.png
一个CBPeripheral有一个或者多个CBService,而每一个CBService有一个或者多个CBCharacteristic,通过可写的CBCharacteristic发送数据,而每一个CBCharacteristic有一个或者多个Description用于描述characteristic的信息或属性
(四)关于蓝牙设备唯一表示的问题
在蓝牙开发中,iOS 没有直接提供获取mac 地址的方法(Android 是可以直接获取的),所以在iOS蓝牙开发中就有唯一标识的问题了
当我们使用CoreBluetooth系统框架进行蓝牙开发的时候,有时候某种功能需要和指定的蓝牙设备进行操作,这就需要我们拿到蓝牙设备的唯一标识,来确定是哪一台设备,先看下一当我们扫描到的蓝牙设备时,所能拿到的属性:
蓝牙设备的属性1.png
蓝牙设备的属性2.png
针对于不同的业务需求,我们在进行连接操作的时候,不要指定具体那一台设备的,那么就可以使用identifier来作为唯一标识
这里有一个坑要注意: 对于同一台蓝牙设备,不同手机进行扫描,然后读取的 identifier是不同的**
而对于需要指定的到蓝牙设备的解决办法:
将mac 地址放在蓝牙设备的广播数据当中,然后在广播的时候,将mac地址一广播的形式发出来
将 mac 地址写在某一个蓝牙特征通道中,当我们连接蓝牙设备之后,通过某一个特征通道获取mac地址
我们可以通过蓝牙设备出厂设备 或者 后期手动修改蓝牙设备的name,作为唯一标识
二、CoreBluetooth常用到的方法
自己封装了一个蓝牙单例的类,对蓝牙开发中常用到的方法写了较为详细的解释,代码如下:
+ (instancetype)shared {
static SLBluetoothCentralManager *
static dispatch_once_t onceT
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
初始化 centralManager
- (instancetype)init {
self = [super init];
if (self) {
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
扫描周周的设备
- (void) sacnNearPerpherals {
TCLog(@"开始扫描四周的设备");
1.第一个参数为Services的UUID(外设端的UUID) 不能为nil
2.第二参数的CBCentralManagerScanOptionAllowDuplicatesKey为已发现的设备是否重复扫描,如果是同一设备会多次回调
[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO}];
#pragma mark - CBCentralManagerDelegate
检查App设备蓝牙是否可用
@param central 中心设备管理器
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
switch (central.state){
case CBCentralManagerStatePoweredOn://蓝牙已打开,开始扫描外设
[self sacnNearPerpherals];
case CBCentralManagerStateUnsupported:
[MBProgressHUD showMessage:@"您的设备不支持蓝牙或蓝牙4.0" toView:nil];
case CBCentralManagerStateUnauthorized:
[MBProgressHUD showMessage:@"未授权打开蓝牙" toView:nil];
case CBCentralManagerStatePoweredOff://蓝牙未打开,系统会自动提示打开,所以不用自行提示
发现外围设备的代理
@param central 中心设备
@param peripheral 外围设备
@param advertisementData 特征数据
@param RSSI 信号强度
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary&NSString *,id& *)advertisementData RSSI:(NSNumber *)RSSI {
NSMutableString* nsmstring=[NSMutableString stringWithString:@"\n"];
[nsmstring appendString:@"----发现外设----\n"];
[nsmstring appendString:@"Peripheral Info:\n"];
[nsmstring appendFormat:@"NAME: %@\n",peripheral.name];
[nsmstring appendFormat:@"UUID(identifier): %@\n",peripheral.identifier];
[nsmstring appendFormat:@"RSSI: %@\n",RSSI];
[nsmstring appendFormat:@"adverisement:%@\n",advertisementData];
TCLog(@"%@",nsmstring);
NSArray *serviceUUIDArr = advertisementData[@"kCBAdvDataServiceUUIDs"];
for (CBUUID *serviceUUID in serviceUUIDArr) {
// 判断外设是否有需要的服务(是否是当前APP对应的外设)&此项目应该判断外设的名字&
if ([serviceUUID.UUIDString isEqualToString:kServiceUUID]) {
//发现符合条件的周边外设通知
[[NSNotificationCenter defaultCenter] postNotificationName: SLDidFoundPeripheralNotification object:peripheral];
[self connectPeripheral:peripheral];
/// 连接指定的设备
- (void)connectPeripheral:(CBPeripheral *)peripheral {
//这个引用不可以省略
self.peripheral =
TCLog(@"----尝试连接设备----\n%@", peripheral);
[self.centralManager connectPeripheral:peripheral
options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
/// 连接外设成功的代理方法
-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
TCLog(@"%@连接成功",peripheral.name);
// 设置设备代理
[self.peripheral setDelegate:self];
[self.peripheral discoverServices:nil];
///连接外设失败的代理方法
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
TCLog(@"%@连接失败",peripheral.name);
///连接外设中断的代理方法
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
TCLog(@"%@连接已断开",peripheral.name);
#pragma mark - CBPeripheralDelegate
/// 获取外设服务的代理
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
TCLog(@"%@获取服务失败:%@",peripheral.name,error.localizedDescription);
for (CBService *service in peripheral.services) {
// 找到对应服务
if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {
//服务中找特征
[service.peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];
///在获取外设服务的代理的方法中如果没有error,可以调用discoverCharacteristics方法请求周边去寻找它的服务所列出的特征,它会响应下面的方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
TCLog(@"%@获取指定特征失败:%@",peripheral.name,error.localizedDescription);
NSMutableString* nsmstring=[NSMutableString stringWithString:@"\n"];
[nsmstring appendFormat:@"------在服务: %@ 中发现 %lu 个特征 ------\n",service.UUID,(unsigned long)service.characteristics.count];
for (CBCharacteristic *characteristic in service.characteristics) {
[nsmstring appendFormat:@"%@\n",characteristic];
[nsmstring appendFormat:@"\n"];
TCLog(@"%@",nsmstring);
self.peripheral =
self.writeCharacteristic =
// 连接成功,开始配对 - 发送第一次校验的数据
[self willPairToPeripheral:peripheral];
///已连接上设备,开始进行配对
- (void)willPairToPeripheral:(CBPeripheral *)peripheral{
//发送第一次校验的数据
NSData *firstAuthData = [SLCheckoutDataUtils firstRandomData];
[[SLBluetoothCentralManager shared] sendCommandData:firstAuthData];
/// 写入数据方法
- (void)sendCommandData:(NSData *)data {
if(self.writeCharacteristic.properties & CBCharacteristicPropertyWrite || self.writeCharacteristic.properties & CBCharacteristicPropertyWriteWithoutResponse) {
[self.peripheral writeValue:data forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
TCLog(@"----写入命令----&:cmd:%@\n\n", data);
TCLog(@"该字段不可写!");
/// 写入数据后的回调方法
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"写入失败: %@",[error localizedDescription]);
NSLog(@"写入成功--&%@",characteristic.value);
[peripheral readValueForCharacteristic:characteristic];
/// 获取到特征的值时回调 -- 获取回调数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
TCLog(@"特征UUID:%@回调数据错误:%@", characteristic.UUID.UUIDString,error.localizedDescription);
TCLog(@"------特征收到回调数据------& uuid:%@ \nvalue: %@\n\n",characteristic.UUID,characteristic.value);
NSString *result = [NSString jkt_hexStringFromData:characteristic.value];
if ([result hasPrefix:SLDidFirstPairSuccessCommand]) {//第一次配对成功
NSData *secondAuthData = [SLCheckoutDataUtils secondVerifyData:characteristic.value];
[[SLBluetoothCentralManager shared] sendCommandData:secondAuthData];
if ([result hasPrefix:SLDidSecondPairSuccessCommand]) {//第二次配对成功
TCLog(@"正式建立的连接-----------");
//开锁测试
[self performSelector:@selector(sendOpenLockCmd) withObject:nil afterDelay:3.0];
对于常用的方法,都写了注释,希望对于第一蓝牙开发的小伙伴有帮助!!
推荐这个库,很?, 对CoreBluetooth进行了封装,如果你不喜欢系统的各种代理方法,那么可以试一试这个库,也许你会喜欢
如果有些的不对的,不吝指教!!!
扬在脸上的自信、长在心底的善良、融进血里的骨气、刻进生命的坚强
这里我们具体说明一下中心模式的应用场景。主设备(手机去扫描连接外设,发现外设服务和属性,操作服务和属性的应用。一般来说,外设(蓝牙设备,比如智能手环之类的东西), 会由硬件工程师开发好,并定义好设备提供的服务,每个服务对于的特征,每个特征的属性(只读,只写,通知等等),本文...
iOS蓝牙开发蓝牙相关基础知识 蓝牙常见名称和缩写 MFI ======= make for ipad ,iphone, itouch 专们为苹果设备制作的设备BLE ==== buletouch low energy,蓝牙4.0设备因为低耗电,所以也叫做BLEp...
首先进一则广告: 蓝牙技术联盟(Bluetooth SIG)日宣布,正式采纳蓝牙4.0核心规范(Bluetooth Core Specification Version 4.0 ),并启动对应的认证计划。会员厂商可以提交其产品进行测试,通过后将获得蓝牙4.0...
原文:http://www.myexception.cn/operating-system/2052286.html iOS开发之蓝牙通讯 一、引言 蓝牙是设备近距离通信的一种方便手段,在iPhone引入蓝牙4.0后,设备之间的通讯变得更加简单。相关的蓝牙操作由专门的Cor...
嘴上说着不要,身体却很诚实嘛。 这是霸道总裁小说里常见的一句话,应用情景的话,老司机大概都懂…… 在实际生活中,这种场景也很常见,嘴上说着我要减肥,我要跑步,我要节食,实际行动却表明了另一种心思,嘴上说着要好好复习,身体却赖在沙发上不想动弹……长期下来,对这样的自己,也很是...
一直以来,好像都在追寻着某种虚无的东西,醒来却徒留下惆怅与失落。 今天是你离开我的第七天,自你离开我后,武汉的天气一直都是阴沉沉的。很抱歉我的反射弧那么长,直到现在才开始悲伤,为着我们之间的感情。或者说,整整七天,没有你的消息,我才真正意识到你已经成了我的过去和回忆。 认真...
《雨》 作者:天洁 一个人打完点滴 窗外的雨 还是没有停 我掏了许久 终于有一把太阳伞 陪我漫步在雨中 雨水撞进水泥地 以为可以 搅起一番风云 不料却让自己 魂飞魄散 收拾好破碎 抱成一团 然后又慢慢 消逝在人间
那是夜色正浓的时分了,我独坐在房间的窗户旁边,望着天外的月,那银白色的光中合着深奥印蓝的天空,使我顿感自然之深奥。 星星在遥远的梦中呼唤着儿时的困惑,不解的眨着眼。其间,不时有流星划过,那奥意的未解使的人类终生探索。 回流的风,旋涡。那相对的互动,使它充满活力。 笑容,这时...iOS中的蓝牙 - 简书
iOS中的蓝牙
iOS中的蓝牙
iOS中提供了4个框架用于实现蓝牙连接
1.GameKit.framework(用法简单)
只能用于iOS设备之间的同个应用内连接,多用于游戏(eg.拳皇,棋牌类),从iOS7开始过期
2.MultipeerConnectivity.framework(代替1)
只能用于iOS设备之间的连接,从iOS7开始引入,主要用于非联网状态下,通过wifi或者蓝牙进行文件共享(仅限于沙盒的文件),多用于附近无网聊天
3.ExternalAccessory.framework(MFi)
可用于第三方蓝牙设备交互,但是蓝牙设备必须经过苹果MFi认证(国内很少)
4.CoreBluetooth.framework(时下热门)
可用于第三方蓝牙设备交互,必须要支持蓝牙4.0
硬件至少是4s,系统至少是iOS6
蓝牙4.0以低功耗著称,一般也叫BLE(Bluetooth Low Energy)
目前应用比较多的案例:运动手环,嵌入式设备,智能家居
设计到的系统/框架
HealthKit/物联网HomeKit/wathOS1,2/iBeacon
GameKit用法
一.准备工作
@property (weak, nonatomic) IBOutlet UIImageView *imageV
// 建立连接
- (IBAction)buildConnect:(id)sender{}
// 发送数据
- (IBAction)sendData:(id)sender{}
二.连接蓝牙
显示可以连接的蓝牙设备列表
- (IBAction)buildConnect:(id)sender {
// 创建弹窗
GKPeerPickerController *ppc = [[GKPeerPickerController alloc] init];
// 设置代理
@interface ViewController () &GKPeerPickerControllerDelegate&
ppc.delegate =
[ppc show];
监听蓝牙的连接
#pragma mark -GKPeerPickerControllerDelegate
// 连接成功就会调用
- (void)peerPickerController:(GKPeerPickerController *)picker // 弹窗
didConnectPeer:(NSString *)peerID // 连接到的蓝牙设备号
toSession:(GKSession *)session // 连接会话(通过它进行数据交互)
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 弹窗消失
[picker dismiss];
三.利用蓝牙传输数据
点击图片从相册中选择一张显示本机
可以修改imaV为Btn,也可以为imaV添加手势
1.修改imageView的用户交互
2.添加手势到图片上
3.拖出手势的响应事件
4.完善相册选择图片代码
// 手势-点击从相册中选一张照片
- (IBAction)tapImage:(UITapGestureRecognizer *)sender {
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 先判断是否有相册
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
// 创建弹出的控制器
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
// 设置图片来源为相册
ipc.sourceType = UIImagePickerControllerSourceTypePhotoL
// 设置代理 @interface ViewController () &UINavigationControllerDelegate, UIImagePickerControllerDelegate&
ipc.delegate =
// modal出来
[self presentViewController:ipc animated:YES completion:nil];
#pragma mark - UINavigationControllerDelegate, UIImagePickerControllerDelegate
// 选中某图片后调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary&NSString *,id& *)info
// 控制器返回
[picker dismissViewControllerAnimated:YES completion:nil];
// 设置图片
self.imageView.image = info[UIImagePickerControllerOriginalImage];
点击发送数据完成图片显示到另一个蓝牙机器上
1.分析需要通过GKSession对象来传递数据,所以在peerPickerController:didConnectPeer:didConnectPeer:的方法中保存session会话
@property (nonatomic, strong) GKSession * /**& 蓝牙连接会话 */
// 连接成功就会调用
- (void)peerPickerController:(GKPeerPickerController *)picker // 弹窗
didConnectPeer:(NSString *)peerID // 连接到的蓝牙设备号
toSession:(GKSession *)session // 连接会话(通过它进行数据交互)
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 弹窗消失
[picker dismiss];
// 保存会话
self.session =
// 发送数据
- (IBAction)sendData:(id)sender {
if (self.imageView.image == nil) // 有图片才继续执行
// 通过蓝牙链接会话发送数据到所有设备
[self.session sendDataToAllPeers:UIImagePNGRepresentation(self.imageView.image) // 数据
withDataMode:GKSendDataReliable // 枚举:发完为止
error:nil];
// 连接成功就会调用
- (void)peerPickerController:(GKPeerPickerController *)picker // 弹窗
didConnectPeer:(NSString *)peerID // 连接到的蓝牙设备号
toSession:(GKSession *)session // 连接会话(通过它进行数据交互)
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 弹窗消失
[picker dismiss];
// 保存会话
self.session =
// 处理接收到的数据[蓝牙设备接收到数据时,就会调用 [self receiveData:fromPeer:inSession:context:]]
// 设置数据接受者为:self
[self.session setDataReceiveHandler:self
withContext:nil];
#pragma mark - 蓝牙设备接收到数据时,就会调用
- (void)receiveData:(NSData *)data // 数据
fromPeer:(NSString *)peer // 来自哪个设备
inSession:(GKSession *)session // 连接会话
context:(void *)context
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
self.imageView.image = [UIImage imageWithData:data];
// 写入相册
UIImageWriteToSavedPhotosAlbum(self.imageView.image, nil, nil, nil);
只能用于iOS设备之间的链接
只能用于同一个应用程序之间的连接
最好别利用蓝牙发送比较大的数据
MultipeerConnectivity
在iOS7中,引入了一个全新的框架——Multipeer Connectivity(多点连接)。
利用Multipeer Connectivity框架,即使在没有连接到WiFi(WLAN)或移动网络(xG)的情况下,距离较近的Apple设备(iMac/iPad/iPhone)之间可基于蓝牙和WiFi(P2P WiFi)技术进行发现和连接实现近场通信。
Multipeer Connectivity扩充的功能与利用AirDrop传输文件非常类似,可以将其看作AirDrop不能直接使用的补偿,代价是需要自己实现。
手机不联网也能跟附近的人聊得火热的FireChat和See You Around等近场聊天App、近距离无网遥控交互拍照神器拍咯App就是基于Multipeer Connectivity框架实现。
相比AirDrop,Multipeer Connectivity在进行发现和会话时并不要求同时打开WiFi和蓝牙,也不像AirDrop那样强制打开这两个开关,而是根据条件适时选择使用蓝牙或(和)WiFi。
粗略测试情况如下:
双方WiFi和蓝牙都未打开:无法发现。
双方都开启蓝牙:通过蓝牙发现和传输。
双方都开启WiFi:通过WiFi Direct发现和传输,速度接近AirDrop(Reliable速率稍低),不知道同一WLAN下是否优先走局域网?
双方都同时开启了WiFi和蓝牙:应该是模拟AirDrop,通过低功耗蓝牙技术扫描发现握手,然后通过WiFi Direct传输。
类似sockaddr,用于标识连接的两端endpoint,通常是昵称或设备名称。
该对象只开放了displayName属性,私有MCPeerIDInternal对象持有的设备相关的_idString/_pid64字段并未公开。
在许多情况下,客户端同时广播并发现同一个服务,这将导致一些混乱,尤其是在client/server模式中。所以,每一个服务都应有一个类型标示符——serviceType,它是由ASCII字母、数字和“-”组成的短文本串,最多15个字符。
MCNearbyServiceAdvertiser
类似broadcaster,可以接收,并处理用户请求连接的响应。但是,这个类会有回调,告知有用户要与您的设备连接,然后可以自定义提示框,以及自定义连接处理。
主线程(com.apple.main-thread(serial))创建MCNearbyServiceAdvertiser并启动startAdvertisingPeer。
MCNearbyServiceAdvertiserDelegate异步回调(didReceiveInvitationFromPeer)切换回主线程。
在主线程didReceiveInvitationFromPeer中创建MCSession并invitationHandler(YES, session)接受会话连接请求(accept参数为YES)。
MCNearbyServiceBrowser
类似servo listen+client connect,用于搜索附近的用户,并可以对搜索到的用户发出邀请加入某个会话中。
主线程(com.apple.main-thread(serial))创建MCNearbyServiceBrowser并启动startBrowsingForPeers。
MCNearbyServiceBrowserDelegate异步回调(foundPeer/lostPeer)切换回主线程。
主线程创建MCSession并启动invitePeer。
启用和管理Multipeer连接会话中的所有人之间的沟通。 通过Sesion,给别人发送数据
注意,peerID并不具备设备识别属性。
类似TCP链接中的socket。创建MCSession时,需指定自身MCPeerID,类似bind。
为避免频繁的会话数据通知阻塞主线程,MCSessionDelegate异步回调(didChangeState/didReceiveCertificate/didReceiveData/didReceiveStream)有一个专门的回调线程——com.apple.MCSession.callbackQueue(serial)。为避免阻塞MCSeesion回调线程,最好新建数据读(写)线程!
MCAdvertiserAssistant/MCBrowserViewController
MCAdvertiserAssistant //可以接收,并处理用户请求连接的响应。没有回调,会弹出默认的提示框,并处理连接。
MCBrowserViewController 弹出搜索框,需要手动modal
MCAdvertiserAssistant为针对Advertiser封装的管理助手;MCBrowserViewController继承自UIViewController,提供了基本的UI应用框架。
MCBrowser/MCAdvertiser的回调线程一般是delegate所在线程Queue:com.apple.main-thread(serial)。
ExteralAccessory
MFI:(make for iPhone/iPad/iTouch)专门为苹果设备制作的设备
支持MFI的设备开发使用此框架
baseK(相关基础知识)
蓝牙常见名称和缩写
BLE:(Bluetooth low energy)蓝牙4.0设备因为低耗电,也叫BLE
peripheral,central:外设和中心设备,发起链接的是central(一般是指手机),被链接的设备是peripheral(运动手环)
service and characteristic:(服务和特征)每个设备会提供服务和特征,类似于服务端的API,但是结构不同.每个设备会有很多服务,每个服务中包含很多字段,这些字段的权限一般分为读(read),写(write),通知(notify)几种,就是我们连接设备后具体需要操作的内容
Description:每个characteristic可以对应一个或者多个Description用于描述characteristic的信息或属性(eg.范围,计量单位)
蓝牙基础知识
CoreBluetooth框架的核心其实是俩东西:peripheral和central,对应他们分别有一组相关的API和类
这两组api粉笔对应不同的业务常见:左侧叫中心模式,就是以你的app作为中心,连接其他的外设的场景;而右侧称为外设模式,使用手机作为外设连接其他中心设备操作的场景
服务和特征(service and characteristic)
每个设备都会有1个or多个服务
每个服务里都会有1个or多个特征
特征就是具体键值对,提供数据的地方
每个特征属性分为:读,写,通知等等
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast
CBCharacteristicPropertyRead
CBCharacteristicPropertyWriteWithoutResponse
CBCharacteristicPropertyWrite
CBCharacteristicPropertyNotify
CBCharacteristicPropertyIndicate
CBCharacteristicPropertyAuthenticatedSignedWrites
CBCharacteristicPropertyExtendedProperties
CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)
CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)
外设,服务,特征的关系
BLE中心模式流程
1.建立中心角色
2.扫描外设(Discover Peripheral)
3.连接外设(Connect Peripheral)
4.扫描外设中的服务和特征(Discover Services And Characteristics)
4.1 获取外设的services
4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
5.利用特征与外设做数据交互(Explore And Interact)
6.订阅Characteristic的通知
7.断开连接(Disconnect)
BLE外设模式流程
1.启动一个Peripheral管理对象
2.本地peripheral设置服务,特征,描述,权限等等
3.peripheral发送广告
4.设置处理订阅,取消订阅,读characteristic,写characteristic的代理方法
蓝牙设备的状态
1.待机状态(standby):设备没有传输和发送数据,并且没有连接到任何外设
2.广播状态(Advertiser):周期性广播状态
3.扫描状态(Scanner):主动搜索正在广播的设备
4.发起链接状态(Initiator):主动向扫描设备发起连接
5.主设备(Master):作为主设备连接到其它设备.
6.从设备(Slave):作为从设备链接到其它设备
蓝牙设备的五种工作状态
准备(Standby)
广播(Advertising)
监听扫描(Scanning)
发起连接(Initiating)
已连接(Connected)
蓝牙和版本使用限制
蓝牙2.0:越狱设备
BLE:iOS6以上
MFI认证设备:无限制
两台BLE设备
如何让iOS模拟器也能测试BLE?
买一个CSR蓝牙4.0 USB适配器,插在Mac上
在终端输入sudo nvram bluetoothHostControllerSwitchBehavior="never"
用Xcode4.6调试代码,将程序跑在iOS6.1模拟器上
苹果把iOS7.0模拟器对BLE的支持移除了
BLE中心模式流程-coding
BLE中心模式流程
1.建立中心角色
2.扫描外设(Discover Peripheral)
3.连接外设(Connect Peripheral)
4.扫描外设中的服务和特征(Discover Services And Characteristics)
4.1 获取外设的services
4.2 获取外设的Characteristics,获取characteristics的值,,获取Characteristics的Descriptor和Descriptor的值
5.利用特征与外设做数据交互(Explore And Interact)
6.订阅Characteristic的通知
7.断开连接(Disconnect)
1.Xcode7.0
3.外设(手机+LightBlue)
1.导入CB头文件,建立主设备管理类,设置主设备代理
#import &CoreBluetooth/CoreBluetooth.h&
@interface XMGBLEController () &CBCentralManagerDelegate&
@property (nonatomic, strong) CBCentralManager *cM /**& 中心管理设备 */
@implementation XMGBLEController
#pragma mark - 懒加载
// 1.建立中心管理者
- (CBCentralManager *)cMgr
if (!_cMgr) {
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
设置主设备的代理,CBCentralManagerDelegate
必须实现的:
- (void)centralManagerDidUpdateState:(CBCentralManager *)//主设备状态改变调用,在初始化CBCentralManager的适合会打开设备,只有当设备正确打开后才能使用
其他选择实现的委托中比较重要的:
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外设
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)//连接外设成功
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)//外设连接失败
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)//断开外设
_cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; // 线程不传默认是主线程
return _cM
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"BLE";
self.view.backgroundColor = [UIColor orangeColor];
[self cMgr];
// 不能在此处扫描,因为状态还没变为打开
//[self.cMgr scanForPeripheralsWithServices:nil options:nil];
2.扫描外设
扫描的方法防治cMgr成功打开的代理方法中
只有设备成功打开,才能开始扫描,否则会报错
#pragma mark - CBCentralManagerDelegate
// 中心管理者状态改变, 在初始化CBCentralManager的时候会打开设备,只有当设备正确打开后才能使用
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
switch (central.state) {
case CBCentralManagerStateUnknown:
NSLog(@"&&&CBCentralManagerStateUnknown");
case CBCentralManagerStateResetting:
NSLog(@"&&&CBCentralManagerStateResetting");
case CBCentralManagerStateUnsupported:
NSLog(@"&&&CBCentralManagerStateUnsupported");
case CBCentralManagerStateUnauthorized:
NSLog(@"&&&CBCentralManagerStateUnauthorized");
case CBCentralManagerStatePoweredOff:
NSLog(@"&&&CBCentralManagerStatePoweredOff");
case CBCentralManagerStatePoweredOn:
NSLog(@"&&&CBCentralManagerStatePoweredOn");
// 2.开始扫描周围的外设
第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
[self.cMgr scanForPeripheralsWithServices:nil options:nil];
// 扫描到设备会进入到此代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary&NSString *,id& *)advertisementData RSSI:(NSNumber *)RSSI
NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
// 接下来连接设备
3.连接外设
扫描手环,打印结果
根据打印结果
// 扫描到设备会进入到此代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary&NSString *,id& *)advertisementData RSSI:(NSNumber *)RSSI
NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
// 3.接下来可以连接设备
//如果你没有设备,可以下载一个app叫lightbule的app去模拟一个设备
//这里自己去设置下连接规则,我设置的是二维码扫描到的运动手环的设备号
// 判断设备号是否扫描到
if ([peripheral.name isEqualToString:@"OBand-75"]) {
一个主设备最多能连7个外设,每个外设最多只能给一个主设备连接,连接成功,失败,断开会进入各自的委托
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)//连接外设成功的委托
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)//外设连接失败的委托
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)//断开外设的委托
// 保存外设,否则方法结束就销毁
self.per =
[self.cMgr connectPeripheral:self.per options:nil];
// 此处Alert提示未扫描到设备,重新扫描
#warning noCode
NSLog(@"没扫描到 &&&&&&&&
%s, line = %d", __FUNCTION__, __LINE__);
// 外设连接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
NSLog(@"&&&连接到名称为(%@)的设备-成功",peripheral.name);
// 外设连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 断开连接(丢失连接)
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
4.扫描外设中的服务和特征
设备链接成功后,就可以扫描设备的服务(services)了,同样是通过代理,扫描到结果后会触发某代理方法.
注意:此时CBCentralManagerDelegate已经不能满足需求,需要新的CBPeripheralDelegate来搞定.
该协议中包含了central与peripheral的许多回调方法
(eg.:获取services,获取characteristics,获取characteristics的值,获取characteristics的Descriptor以及Descriptor的值,写数据,读RSSI,用通知的方式订阅数据等等).
4.1 获取外设的services
首先设置外设的代理,并搜寻services
然后在代理方法peripheral:didDiscoverServices:中遍历services
// 外设连接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
NSLog(@"&&&连接到名称为(%@)的设备-成功",peripheral.name);
//设置的peripheral代理CBPeripheralDelegate
//@interface ViewController : UIViewController&CBCentralManagerDelegate,CBPeripheralDelegate&
[peripheral setDelegate:self];
//扫描外设Services,成功后会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
[peripheral discoverServices:nil];
Discovers the specified services of the peripheral.
An array of CBUUID objects that you are interested in. Here, each CBUUID object represents a UUID that identifies the type of service you want to discover.
#pragma mark - CBPeripheralDelegate
// 发现外设的service
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
if (error)
NSLog(@"&&&Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
for (CBService *service in peripheral.services) {
NSLog(@"service.UUID = %@", service.UUID);
//扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
[peripheral discoverCharacteristics:nil forService:service];
4.2 获取外设的characteris,获取Characteristics的值,获取Characteristics的Descriptor以及Descriptor的值
// 外设发现service的特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
if (error)
NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
for (CBCharacteristic *characteristic in service.characteristics)
NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
#warning noCodeFor 优化,分开写是为了让大家看注释清晰,并不符合编码规范
//获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral readValueForCharacteristic:characteristic]; // 外设读取特征的值
//搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
[peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外设发现特征的描述
// 获取characteristic的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
//打印出characteristic的UUID和值
//!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据
NSLog(@"%s, line = %d, characteristic.UUID:%@
value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);
// 获取Characteristics的 descriptor的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
//打印出DescriptorsUUID 和value
//这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析
NSLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);
// 发现特征Characteristics的描述Descriptor
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
for (CBDescriptor *descriptor in characteristic.descriptors) {
NSLog(@"descriptor.UUID:%@",descriptor.UUID);
5.写数据到特征中
// 5.将数据写入特征(自定义方法,为了看的更清楚,没别的意思)
- (void)yf_peripheral:(CBPeripheral *)peripheral writeData:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic
typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast
CBCharacteristicPropertyRead
CBCharacteristicPropertyWriteWithoutResponse
CBCharacteristicPropertyWrite
CBCharacteristicPropertyNotify
CBCharacteristicPropertyIndicate
CBCharacteristicPropertyAuthenticatedSignedWrites
CBCharacteristicPropertyExtendedProperties
CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)
CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)
打印出特征的权限(characteristic.properties),可以看到有很多种,这是一个NS_OPTIONS的枚举,可以是多个值
常见的又read,write,noitfy,indicate.知道这几个基本够用了,前俩是读写权限,后俩都是通知,俩不同的通知方式
NSLog(@"%s, line = %d, characteristic.properties:%d", __FUNCTION__, __LINE__, characteristic.properties);
// 只有特征的properties中有写的属性时候,才写
if (characteristic.properties & CBCharacteristicPropertyWrite) {
// 这句才是正宗的核心代码
[peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
6.订阅特征的通知
// 设置通知
- (void)yf_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
// 设置通知, 数据会进入 peripheral:didUpdateValueForCharacteristic:error:方法
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
// 取消通知
- (void)yf_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
7.断开连接
// 7.断开连接
- (void)yf_cMgr:(CBCentralManager *)cMgr stopScanAndDisConnectWithPeripheral:(CBPeripheral *)peripheral
// 停止扫描
[cMgr stopScan];
// 断开连接
[cMgr cancelPeripheralConnection:peripheral];
BLE-periphral外设模式流程
之前在基础知识介绍过BLE应用的两种流程
central模式用的都是左边的类,而peripheral模式用的是右边的类
peripheral模式的流程
1.引入CoreBluetooth框架,初始化peripheralManager
2.设置peripheralManager中的内容
3.开启广播advertising
4.对central的操作进行响应
4.1 读characteristics请求
4.2 写characteristics请求
4.4 订阅和取消订阅characteristics
真机(4s以上)
具体操作步骤
1.引入CoreBluetooth框架,初始化peripheralManager
#import &CoreBluetooth/CoreBluetooth.h&
@interface XMGBLEPeripheralViewController () &CBPeripheralManagerDelegate&
@property (nonatomic, strong) CBPeripheralManager *pM /**& 外设管理者 */
@implementation XMGBLEPeripheralViewController
- (CBPeripheralManager *)pMgr
if (!_pMgr) {
_pMgr = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
return _pM
- (void)viewDidLoad {
[super viewDidLoad];
// 调用get方法初始化,初始化后CBPeripheralManager状态改变会调用代理方法peripheralManagerDidUpdateState:
// 模拟器永远也不会是CBPeripheralManagerStatePoweredOn状态
[self pMgr];
2.设置peripheralManager中的内容
创建characteristics及其description,
创建service,把characteristics添加到service中,
再把service添加到peripheralManager中
#pragma mark - CBPeripheralManagerDelegate
// CBPeripheralManager初始化后会触发的方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
// 提示设备成功打开
[SVProgressHUD showSuccessWithStatus:@"xmg设备打开成功~"];
// 配置各种服务入CBPeripheralManager
[self yf_setupPMgr];
// 提示设备打开失败
[SVProgressHUD showErrorWithStatus:@"失败!"];
#pragma mark - 私有方法
- (void)yf_setupPMgr
// 特征描述的UUID
CBUUID *characteristicUserDescriptionUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
// 特征的通知UUID
CBUUID *notifyCharacteristicUUID = [CBUUID UUIDWithString:notiyCharacteristicStrUUID];
// 特征的读写UUID
CBUUID *readwriteCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID];
// 特征的只读UUID
CBUUID *readCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID];
CBUUID *ser1UUID = [CBUUID UUIDWithString:Service1StrUUID];
CBUUID *ser2UUID = [CBUUID UUIDWithString:Service2StrUUID];
// 初始化一个特征的描述
CBMutableDescriptor *des1 = [[CBMutableDescriptor alloc] initWithType:characteristicUserDescriptionUUID value:@"xmgDes1"];
// 可通知的特征
CBMutableCharacteristic *notifyCharacteristic = [[CBMutableCharacteristic alloc] initWithType:notifyCharacteristicUUID // UUID
properties:CBCharacteristicPropertyNotify // 枚举:通知
value:nil // 数据先不传
permissions:CBAttributePermissionsReadable]; // 枚举:可读
// 可读写的特征
CBMutableCharacteristic *readwriteChar = [[CBMutableCharacteristic alloc] initWithType:readwriteCharacteristicUUID
properties:CBCharacteristicPropertyRead | CBCharacteristicPropertyWrite
permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
[readwriteChar setDescriptors:@[des1]]; // 设置特征的描述
// 只读特征
CBMutableCharacteristic *readChar = [[CBMutableCharacteristic alloc] initWithType:readCharacteristicUUID
properties:CBCharacteristicPropertyRead
permissions:CBAttributePermissionsReadable];
// 初始化服务1
CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES];
// 为服务设置俩特征(通知, 带描述的读写)
[ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]];
// 初始化服务2,并且添加一个只读特征
CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES];
ser2.characteristics = @[readChar];
// 添加服务进外设管理者
// 添加操作会触发代理方法peripheralManager:didAddService:error:
[self.pMgr addService:ser1];
[self.pMgr addService:ser2];
3.开启广播
// 添加服务进CBPeripheralManager时会触发的方法
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error
// 由于添加了两次ser,所以方法会调用两次
static int i = 0;
if (!error) {
// 当第二次进入方法时候,代表两个服务添加完毕,此时要用到2,由于没有扩展性,所以新增了可变数组,记录添加的服务数量
if (i == self.servieces.count) {
// 广播内容
NSDictionary *advertDict = @{CBAdvertisementDataServiceUUIDsKey: [self.servieces valueForKeyPath:@"UUID"],
CBAdvertisementDataLocalNameKey:LocalNameKey};
// 发出广播,会触发peripheralManagerDidStartAdvertising:error:
[peripheral startAdvertising:advertDict];
// 开始广播触发的代理
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error
&&&&&&&&分割线&&&&下面是修改的地方
@property (nonatomic, strong) NSMutableArray * /**& 服务可变数组 */
// 自定义服务
- (NSMutableArray *)servieces
if (!_servieces) {
_servieces = [NSMutableArray array];
#pragma mark - 私有方法
- (void)yf_setupPMgr
// 初始化服务1
CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES];
// 为服务设置俩特征(通知, 带描述的读写)
[ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]];
[self.servieces addObject:ser1];
// 初始化服务2,并且添加一个只读特征
CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES];
ser2.characteristics = @[readChar];
[self.servieces addObject:ser2];
// 添加服务进外设管理者
// 添加操作会触发代理方法peripheralManager:didAddService:error:
if (self.servieces.count) {
for (CBMutableService *ser in self.servieces) {
[self.pMgr addService:ser];
4.对central的操作做出响应
4.1 读characteristics请求
4.2 写characteristics请求
4.3 订阅和取消订阅characteristics
// 外设收到读的请求,然后读特征的值赋值给request
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 判断是否可读
if (request.characteristic.properties & CBCharacteristicPropertyRead) {
NSData *data = request.characteristic.
request.value =
// 对请求成功做出响应
[self.pMgr respondToRequest:request withResult:CBATTErrorSuccess];
[self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
// 外设收到写的请求,然后读request的值,写给特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray&CBATTRequest *& *)requests
NSLog(@"%s, line = %d, requests = %@", __FUNCTION__, __LINE__, requests);
CBATTRequest *request = requests.firstO
if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
NSData *data = request.
// 此处赋值要转类型,否则报错
CBMutableCharacteristic *mChar = (CBMutableCharacteristic *)request.
mChar.value =
// 对请求成功做出响应
[self.pMgr respondToRequest:request withResult:CBATTErrorSuccess];
[self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
// 与CBCentral的交互
// 订阅特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic
NSLog(@"%s, line = %d, 订阅了%@的数据", __FUNCTION__, __LINE__, characteristic.UUID);
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(yf_sendData:)
userInfo:characteristic
repeats:YES];
self.timer =
/* 另一种方法 */
NSTimer *testTimer = [NSTimer timerWithTimeInterval:2.0
target:self
selector:@selector(yf_sendData:)
userInfo:characteristic
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:testTimer forMode:NSDefaultRunLoopMode];
// 取消订阅特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic
NSLog(@"%s, line = %d, 取消订阅了%@的数据", __FUNCTION__, __LINE__, characteristic.UUID);
[self.timer invalidate];
self.timer =
- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 计时器每隔两秒调用的方法
- (BOOL)yf_sendData:(NSTimer *)timer
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yy:MM:dd:HH:mm:ss";
NSString *now = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"now = %@", now);
// 执行回应central通知数据
[self.pMgr updateValue:[now dataUsingEncoding:NSUTF8StringEncoding]
forCharacteristic:timer.userInfo
onSubscribedCentrals:nil];
iBeacon简介
iBeacon起源:苹果在WWDC2013上正式推出了iBeacon,并且在iOS7设备商配置了该功能
iBeacon应用:苹果期望将其作为一种技术标准,这个标准允许移动App(包括iOS和Android设备)监听来自于iBeacon设备上的信号并作出响应.
iBeacon设备:配备有BLE通信功能,并使用BLE向周围发送自己特有的ID,移动设备上的App在接收到该ID后可以作出相应的反应.比如,我们在店铺里设置iBeacon发射器,便可以让应用接收到信息并将这一信息通知给服务器,服务器向我们的App返回与该店铺相关的产品或折扣信息.
本质上讲,iBeacon技术允许App了解他们在某个局部范围内的位置,并向用户分发基于位置的超文本上下文内容.
简单开发流程
1.初始化iBeacon的区域,以及区域管理者
#import &CoreLocation/CoreLocation.h&
@interface AppDelegate () &CLLocationManagerDelegate&
@property (nonatomic, strong) CLBeaconRegion *beaconR /**& beacon区域 */
@property (nonatomic, strong) CLLocationManager *locM /**& 位置管理者 */
@implementation AppDelegate
#pragma mark - lazy
// 懒加载iBeacon区域
- (CLBeaconRegion *)beaconRegion
if (!_beaconRegion) {
NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:@"416C80-A67C-A2A9BB166D0F"];
_beaconRegion = [[CLBeaconRegion alloc] initWithProximityUUID:proximityUUID
identifier:@"brID"];
一个App为了在特定商场提?高?用户体验,可?用使?用相同的proximity UUID来监听商场的所有商铺。当?用户进?入?一个商店时,App检测商铺的iBeacon设备并使?用major和 minor值来获取额外的信息,如?用户进?入哪家商店或?用户在商店的哪个区域(注意:虽然每个iBeacon都必须有?一个proximity UUID,但 major和minor的值是可选的)。
return _beaconR
// 懒加载创建地域管理者
- (CLLocationManager *)locMgr
if (!_locMgr) {
_locMgr = [[CLLocationManager alloc] init];
_locMgr.delegate =
return _locM
2.进入退出时候的操作
#pragma mark - CLLocationManagerDelegate
// 开始监听
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
// 进入监控的region区域
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
if ([region isEqual:self.beaconRegion]) {
// Start calculating ranges for beacons in the specified region.
// 开始计算beaconRegion区域内部的iBeacon设备数量,确定我们的设备与区域中的一个或多个iBeacon设备的相对距离,并在距离改变时被通知,触发代理 didRangeBeacons
[self.locMgr startRangingBeaconsInRegion:self.beaconRegion];
NSDictionary *info = [self.beaconRegion peripheralDataWithMeasuredPower:@0];
// 通知外设开启广播
[[NSNotificationCenter defaultCenter] postNotificationName:@"didEnterRegionNotification" object:nil userInfo:info];
// 退出监控的region区域
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
// 外设关闭广播
// 通知外设开启广播
[[NSNotificationCenter defaultCenter] postNotificationName:@"didExitRegionNotification" object:nil];
// 当指定Beacon区域的iBeacon设备进?入范围、离开范围或相对距离改变时,CLLocationManager对象调?用代理对象的 locationManager:didRangeBeacons:inRegion:
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray&CLBeacon *& *)beacons inRegion:(CLBeaconRegion *)region
// beacons表?示当前设备范围内的iBeacon。
// iBeacon的数组根据离设备的相对距离来排序,最近的在最前?面。
// 我们可以使?用这些对象中的信息来确定?用户离每个iBeacon设备的距离。 CLBeacon对象(数组元素)的proximity属性给出了(手机)到?一个beacon的相对距离
// 注意:iBeacon的排列依赖于检测到的BLE?无线信号的强度,以及这些信号受墙壁、门或其它物理实体的影响。当我们使?用iBeacon时需要考虑 这些影响因素。
if (beacons.count) {
for (NSInteger i = 0; i & beacons. i++) {
CLBeacon *beacon = beacons[i];
typedef NS_ENUM(NSInteger, CLProximity) {
CLProximityUnknown,
CLProximityImmediate,
CLProximityNear,
CLProximityFar
} NS_ENUM_AVAILABLE_IOS(7_0) __WATCHOS_PROHIBITED;
if (beacon.proximity == CLProximityNear) {
NSLog(@"major = %@|| minor = %@", beacon.major, beacon.minor);
// 注意:当多个iBeacon设备广告了相同的proximityUUID, major和minor属性组合时,在locationManager:didRangeBeacons:inRegion:方法 中它们可能会有不同的距离与精度。建议每?一个beacon设备都是唯?一标识的。
- (void)locationManager:(CLLocationManager *)manager rangingBeaconsDidFailForRegion:(CLBeaconRegion *)region withError:(NSError *)error
NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
3.外设模式给它广播
#import &CoreBluetooth/CoreBluetooth.h&
@interface ViewController () &CBPeripheralManagerDelegate&
@property (nonatomic, strong) CBPeripheralManager *pM /**& 外设管理模式 */
@implementation ViewController
// 懒加载创建
- (CBPeripheralManager *)pMgr
if (!_pMgr) {
_pMgr = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
return _pM
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 先初始化外设管理者
[self pMgr];
[[NSNotificationCenter defaultCenter] addObserverForName:@"didEnterRegionNotification"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification * _Nonnull note) {
// 开始广播位置信息proximity UUID(及major或minor值)
if (self.pMgr.state == CBPeripheralManagerStatePoweredOn) {
[self.pMgr startAdvertising:note.userInfo];
[[NSNotificationCenter defaultCenter] addObserverForName:@"didExitRegionNotification"
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification * _Nonnull note) {
if (self.pMgr.isAdvertising) {
[self.pMgr stopAdvertising];
- (void)dealloc
// 实际上控制器中不写也不会出问题,此处只是为了 代码规范
[[NSNotificationCenter defaultCenter] removeObserver:self];
#pragma mark - CBPeripheralManagerDelegate
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral
if (peripheral.state == CBPeripheralManagerStatePoweredOn) {
苹果在2010推出的OS X 10.7 Lion系统中加入了全新的AirDrop功能,该功能允许两台Mac机之间无线传输文件。
区别于传统的局域网文件共享方式,AirDrop不要求两台机器在同一个网络内。
用户无需设置,只需要打开AirDrop文件夹即可查看到其他用户,分享文件变得非常便捷。
AirDrop不需要基于(无线)路由器或者手动建立热点组网,它是利用Mac与Mac之间的点对点网络来进行会话传输。
这一切由系统在后台完成,无需断开当前WiFi网络,也不影响当前连接WiFi网络的通信,就可以与其他Mac通过内置特定信道通信。
WWDC13上推出的iOS7也开始支持iOS设备之间使用AirDrop实现共享传输。
关于AirDrop的条件要求及内部机制,可参考。
WWDC14推出的OS X 10.10 Yosemite操作系统,终于打通了与iOS移动设备之间的。
运行Mac OS X Yosemite 10.10版本的Mac设备(型号≥2012)和运行iOS 7及以上的iOS设备(≥iPhone5,≥iPad 4,iPad mini,≥iPod touch)之间才能实现跨平台文件传输。
根据官方资料显示,AirDrop基于蓝牙和WiFi实现(AirDrop does the rest using Wi-Fi and Bluetooth)。
具体来说,通过低功耗蓝牙技术()进行发现(Advertising/Browsing),使用技术进行数据传输。
可参考《》《》。
因此,开启AirDrop不要求双方必须联网或连接到同一局域网,但必须同时打开WiFi和蓝牙,且进行传输的两台设备必须保持在9米的范围之内。
iOS中提供了4个框架用于实现蓝牙连接 GameKit.framework(用法简单)-只能用于iOS设备之间的同个应用内连接,多用于游戏(eg.拳皇,棋牌类),从iOS7开始过期 MultipeerConnectivity.framework(代替1)-只能用于iOS设备...
CoreBluetooth 简介CoreBlueTooth.framework使用 CoreBluetooth 要求设备必须要支持蓝牙4.0(一般也叫BLE)。,并且手机型号必须是iPhone4以上,也就是至少4s手机.使用CoreBluetooth进行开发可实现与第三方设...
在上篇文章中我们提到了 iOS 开发中,使用GameKit 框架实现相同网络的 iOS 设备之间传输数据.但是 GameKit 框架在 iOS7 之后就过时了,那么本文将介绍另一种关于蓝牙的框架 CoreBluetooth. CoreBluetooth 简介 CoreBlu...
蓝牙开发之第一次: 忙完IOMix,还在研究iOS的音频框架,老板突然就说要先做蓝牙相关的项目了。于是就开始了第一次开发iOS蓝牙应用。两周时间,厘清了很多之前模糊的地方。 首先有三个事情需要说明: 1、BLE(蓝牙4.0)可以实现1连多(我做的项目就是1台手机连接8个蓝牙...
有钱借给别人是好事,说明经济宽裕,还有点闲钱,但也可能是坏事,一不小心就成了小人。 一哥们,平时一起混得不错,虽未一起同过窗,也未一起扛过枪,当然更没有一起嫖过娼,但一起玩,一起赌。借钱的事,还得从赌说起。赢钱的时候,哥俩好,一起吃吃喝喝,输钱了,输到钱包都空了,只好向朋友...
不置可否的年代,旁白或许太多无奈。聆听完于娟的事迹,让我心情难耐,本该意气风发的年纪,却被无情的屠宰!想赚钱想大房想有车想许多.可最后却忘记了那最应该想到的健康,承认物质的每一年每一代,钱可以得到许多许多,也不避讳失去的许多,不该在三十的年纪思考这般问题,却又不得不考虑健康...
原创作者:天河奔骁
图片来源:网络空间 怕接陌生电话。有时接个陌生电话,对方叽里咕噜,说一通你完全不懂的方言,闹了半天,原来是错拨号码了!害得浪费你时间。 有时,正巧手头有事,或者刚刚进入美梦,电话铃一声催得紧似一声,你停下手里活计,或努力赶走睡意,刚接通电话,你刚想...
有了这个改装利器,汽车音响改装可以变得非常简单。 一次偶然的机会,在朋友车上听了汽车音响改装的效果,感觉声音非常清晰通透,细节也非常真实。 坐在车上,听着美妙的音乐效果,这种感觉非常不错,不知不觉就到了目的地。 再三追问之下,朋友“老实交代” 了这种音响升级的秘密!—— 进...
一个人的智商决定了他与谁竞争,而情商决定最终谁能够嬴。其实每个人生活圈子里的人,从智商水平上看都差不多,那为什么会有的人活得生无可恋,而有的人却风生水起。究其二者之间的区别在于情商。也就是平常待人处世的方式的区别。 1.在团队中不要一开始就锋芒毕露,这很容易遭人嫉妒,从而产...

我要回帖

更多关于 bluetooth蓝牙驱动 的文章

 

随机推荐