首页 > 其他分享 >iOS关于蓝牙连接的简单介绍与使用

iOS关于蓝牙连接的简单介绍与使用

时间:2022-11-29 18:07:20浏览次数:37  
标签:iOS UUID 蓝牙 peripheral NSLog mark void pragma 连接


下面是两台iPhone6连接同一台蓝牙设备的结果:

**成功连接**** peripheral: <CBPeripheral: 0x1700f4500, identifier = 50084F69-BA5A-34AC-8A6E-6F0CEADB21CD, name = 555555555588,
state = connected> with UUID: <__NSConcreteUUID 0x17003d980> 50084F69-BA5A-34AC-8A6E-6F0CEADB21CD**
****
****
**成功连接**** peripheral: <CBPeripheral: 0x1742e3000, identifier = 55B7D759-0F1E-6271-EA14-BC5A9C9EEEEC, name = 555555555588,
state = connected> with UUID: <__NSConcreteUUID 0x174036c00> 55B7D759-0F1E-6271-EA14-BC5A9C9EEEEC**

iOS的蓝牙开发很简单,只要包含一个库,创建CBCentralManager实例,实现代理方法,然后就可以直接和设备进行通信。


#import <CoreBluetooth/CoreBluetooth.h>

首先可以定义一些即将使用到的UUID的宏

​#define kPeripheralName @"360qws Electric Bike Service" //外围设备名称 ​​​​#define kServiceUUID @"7CACEB8B-DFC4-4A40-A942-AAD653D174DC" //服务的UUID ​

#define kCharacteristicUUID @"282A67B2-8DAB-4577-A42F-C4871A3EEC4F" //特征的UUID
如果不是把手机作为中心设备的话,这些没有必要设置。

#define kCharacteristicUUID @"282A67B2-8DAB-4577-A42F-C4871A3EEC4F" //特征的UUID


1.设备的UUID以及characteristic,可以把他们写成宏

#define TRANSFER_SERVICE_UUID           @"0000fff0-0000-1000-8000-00206f9c56cad"

#define TRANSFER_CHARACTERISTIC_UUID    @"0000fff7-0000-1000-8000-00806f9c56cad"

2.在.h文件中导入两个头文件,并在接口中实现两个协议

#import"ViewController.h"

#import<CoreBluetooth/CoreBluetooth.h>

//需要实现协议

@interfaceViewController () <CBCentralManagerDelegate,CBPeripheralDelegate>{}


3.创建两个蓝牙设备属性,一个相当于主机,一个相当于外设从机


#pragma mark 蓝牙设备

@property (strong,nonatomic)CBCentralManager   *centralManager;        //接收

@property (strong,nonatomic)CBPeripheral       *discoveredPeripheral;  //外设



@end


4.开始蓝牙配置


#pragma mark  在初始化界面结束后设置自己为代理

@implementation

- (void)viewDidLoad {

    [superviewDidLoad];

  _centralManager = [[CBCentralManageralloc]initWithDelegate:selfqueue:nil];

}

#pragma mark  此处监控一下central的状态值,可以判断蓝牙是否开启/可用

- (void)centralManagerDidUpdateState:(CBCentralManager

{

NSMutableString *stringForCentralManagerState = [NSMutableStringstringWithString:@"UpdateState:"];

switch (central.state) {

       caseCBCentralManagerStateUnknown:

appendString:@"Unkown\n"];

break;

       caseCBCentralManagerStateUnsupported:

appendString:@"Unsupported\n"];

       caseCBCentralManagerStateUnauthorized:

appendString:@"Unauthorized\n"];

       caseCBCentralManagerStateResetting:

appendString:@"Resetting\n"];

       caseCBCentralManagerStatePoweredOff:

appendString:@"PowerOff\n"];

       caseCBCentralManagerStatePoweredOn:

           //设备支持BLE并且可用

appendString:@"PoweredOn\n"];

//开始搜索

selfscan];

break;

default:

appendString:@"none\n"];

break;

    }

NSLog(@"%@", stringForCentralManagerState);

}


#pragma mark 扫描

- (void)scan

{           [self.centralManage scanForPeripheralsWithServices:@[[CBUUI UUIDWithString:TRANSFER_SERVICE_UUID]]

 options:@{CBCentralManagerScanOptionAllowDuplicatesKey :@YES}];

    NSLog(@"Scanning started");

}


#pragma mark 发现设备,连接

//一旦符合要求的设备被发现,就会回调此方法

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber

{

NSLog(@"Discovered %@ at %@", peripheral.name, RSSI);

if (self.discoveredPeripheral

self.discoveredPeripheral

// 连接

self.centralManagerconnectPeripheral:peripheraloptions:nil];

NSLog(@"Connecting to peripheral %@", peripheral);

    }

}



#pragma mark 未能连接的处理方法

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError

{

   NSLog(@"Failed to connect to %@. (%@)", peripheral, [errorlocalizedDescription]);

}




#pragma mark 当连接上设备

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral

{

   NSLog(@"Peripheral Connected");

    

   //已连接上设备,故停止搜索

    [self.centralManagerstopScan];

   NSLog(@"Scanning stopped");

    

delegate =self;

    

   //寻找指定UUID的Service

    [peripheraldiscoverServices:@[[CBUUIDUUIDWithString:TRANSFER_SERVICE_UUID]]];

}

#pragma mark 发现设备上指定Service会回调此处

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

{

if

       NSLog(@"Error discovering services: %@", [errorlocalizedDescription]);

return;

    }

   //寻找指定UUID的Characteristic

for (CBService *servicein peripheral.services) {

        [peripheraldiscoverCharacteristics:@[[CBUUIDUUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]

forService:service];

    }

}

#pragma mark 找到指定UUID的Characteristic会回调此处

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

{

if

       NSLog(@"Error discovering characteristics: %@", [errorlocalizedDescription]);

return;

    }

for (CBCharacteristic *characteristicin service.characteristics) {

if ([characteristic.UUIDisEqual:[CBUUIDUUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {

           NSLog(@"find the characteristic");

setNotifyValue:YESforCharacteristic:characteristic];

        }

    }

}

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

{

if

              NSLog(@"Error discovering characteristics: %@", [errorlocalizedDescription]);

return;

    }

NSLog(@"value --> %@",characteristic.value);

#pragma mark 把接收到的数据进行截取

//此处我们就可以拿到value值对其进行数据解析了

NSData *data = characteristic.value;

 }



#pragma mark 蓝牙断开后自动重连

-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError

{

   NSLog(@"Peripheral Disconnected");

   self.discoveredPeripheral =nil;

   // 重新开启搜索

selfscan];

    

   UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"蓝牙连接状态"message:@"连接已断开"delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:@"关闭",nil];

show];

}


5.蓝牙后台运行

若要实现蓝牙4.0在APP进入后台时仍能工作,传输数据,不用写代码,只需要修改xxx-info.plist文件即可


Required background modes中加入两项


App shares data using CoreBluetooth  和   App communicates using CoreBluetooth

标签:iOS,UUID,蓝牙,peripheral,NSLog,mark,void,pragma,连接
From: https://blog.51cto.com/u_15894905/5896175

相关文章

  • 推荐大家在GitHub 上值得关注学习的 iOS 开源项目
    GitHub上有很多不错的iOS开源项目,和大家特别推荐以下几个项目:1.ReactiveCocoaGitHub链接:​​ReactiveCocoa/ReactiveCocoa​​GitHub自家的函数式响应式编程范式的Objecti......
  • windows SVN服务器:由于目标计算机积极拒绝,无法连接
    今天和同事整外网svn,出现了几个问题。我的win10电脑当做svn服务器(安装visualSVN客户端),我同事访问我的电脑。我们俩同时连接到我都WiFi热点(相当于路由器)。1、ping不通我......
  • ios中getTime()的兼容性问题
    时间格式为:2017-12-1212:00:00在苹果上获取时间戳有兼容性问题 需要转换成2017/12/1212:00:00 才可以正确获取到时间戳 vargetTime=function(time){varmyDate......
  • 集WIFI、蓝牙连接的2.4寸串口屏智能烤箱应用方案
    近年来由于烹饪潮的持续风靡,烹饪行业正展现出强大的市场潜力。中国饮食文化源远流长,烹调技艺各具风韵,其中,煎、烤、炸类美食广受人们的欢迎。酥香松脆的煎烤美食,能够让身体......
  • iOS项目Flutter混合工程CI自动化配置
    CI整个流程简介:flutter项⽬源码仓库配置CI命令,配置runner与源码关联起来,flutter项⽬源码更新时,触发CI命令通过runner机器将flutter源码⽣成framework,然后通过git命令将⽣......
  • axios拦截code码,错误处理。vue2版本
    直接上代码importaxiosfrom'axios'import{Notification}from'element-ui';constrequest=axios.create({timeout:10000})//response拦截器获取后......
  • 汇编实验:基于BIOS调用(10H)的多窗口输出程序
    汇编实验报告-屏幕窗口程序实验1.题目要求:自行编写一个键盘输入并且在屏幕输出的程序,它可以完成键盘读入并且在屏幕显示出来。具体要求:2.运行环境:Windows11+MASM3.......
  • iOS开发_Masonry使用
    本文主要会讲到masonry英文文档(见上面的git地址)中提及到的使用说明,以及个人使用过程中的一些经验,仅适用一些刚使用masonry的新手,大牛可以忽略,当然也可以进来指点。1、......
  • 实验五:全连接神经网络手写数字识别实验
    【实验目的】理解神经网络原理,掌握神经网络前向推理和后向传播方法;掌握使用pytorch框架训练和推理全连接神经网络模型的编程实现方法。【实验内容】1.使用pytorch框架,......
  • 实现序号连接线的一种样式列表
    实现一种序号的连接线,类似于element-ui组件库里面的时间线组件,在工作中,这种样式的列表经常见到,如下图:这种列表在vue里面样式的实现,废话不多说,直接上图这样的列表样式h......