博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS蓝牙开发
阅读量:7045 次
发布时间:2019-06-28

本文共 5852 字,大约阅读时间需要 19 分钟。

蓝牙基础知识

蓝牙库

当前iOS中的蓝牙开发使用的都是系统自带的蓝牙库<CoreBluetooth/CoreBluetooth.h>

蓝牙设备版本要求

蓝牙设备必须是4.0或者以上

CoreBluetooth框架的核心

CoreBluetooth框架中的核心是peripheral和central, 它们分别表示外设和中心,设备上可以认为手机就是中心, 蓝牙设备就是外设

服务和特征

蓝牙设备它有若干个服务service,每个服务里面有包含若干个特征characteristic,特征就是提供数据的地方

外设, 服务, 特征间的关系

CoreBluetooth框架的架构

连接蓝牙的具体实现

实现流程

1.建立中心角色

2.扫描外设
3.连接外设
4.获取外设中的服务和特征
5.与外设做交互

实现步骤

1.导入CoreBluetooth头文件,添加代理,建立中心角色

#import 
@interface ViewController : UIViewController
@property (strong, nonatomic) CBCentralManager *centralManager; //蓝牙管理者@property(strong,nonatomic)CBPeripheral *peripheral; //存储匹配成功的外设-(void)viewDidLoad { [super viewDidLoad]; //初始化,最后一个线程参数可以为nil,默认是main线程 self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];}复制代码

2.扫描外设

/*    1.初始化成功会自动调用    2.必须实现的代理,返回centralManager的状态    3.只有在状态为CBManagerStatePoweredOn的情况下才可以开始扫描外设*/-(void)centralManagerDidUpdateState:(CBCentralManager *)central {    switch (central.state) {        case CBManagerStateUnknown:            NSLog(@">>>未知");            break;        case CBManagerStateResetting:            NSLog(@">>>重置");            break;        case CBManagerStateUnsupported:            NSLog(@">>>设备不支持");            break;        case CBManagerStateUnauthorized:            NSLog(@">>>设备未授权");            break;        case CBManagerStatePoweredOff:        {            NSLog(@">>>设备关闭");            self.bleStatusBlock(NO);        }            break;        case CBManagerStatePoweredOn:        {            NSLog(@">>>设备打开");             //开始扫描外设, 然后会进入didDiscoverPeripheral方法            /*                1. 两个参数为nil表示默认扫描所有可见的蓝牙设备                2. 第一个参数用来设置扫描有指定服务的外设                3. 第二个参数用来设置是否重复扫描已经发现的设备                                NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBCentralManagerScanOptionAllowDuplicatesKey];                                Bool值为Yes,表示重复扫描, 反之表示不会重复扫描                            */            [self.centralManager scanForPeripheralsWithServices:nil options:nil];        }            break;                    default:            break;    }}复制代码

连接外设

//扫描到的设备可以在这个方法里面打印-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(nonnull CBPeripheral *)peripheral advertisementData:(nonnull NSDictionary
*)advertisementData RSSI:(nonnull NSNumber *)RSSI { NSLog(@">>>advertisementData :%@ name :%@ ",advertisementData,peripheral.name); //有些产品是根据Mac地址来进行配对, 在这里我们就可以拿到,具体什么规则, 根据各个蓝牙设备来定 NSData *data = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"]; //解析 //..... if(自己的判断) { //找到的设备必须持有它,否则CBCentralManager中也不会保存peripheral,那么CBPeripheralDelegate中的方法也不会被调用!! self.peripheral = peripheral; //停止扫描 [self.centralManager stopScan]; //连接外设 [_centralManager connectPeripheral:peripheral options:nil]; }}//连接到Peripherals-成功- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{ NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);}//连接到Peripherals-失败-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{ NSLog(@">>>连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);}//Peripherals断开连接- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{ NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);}复制代码

获取外设中的服务和特征

//连接外设成功-(void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {        NSLog(@">>>连接到名称为(%@)的设备-成功",peripheral.name);    peripheral.delegate=self;//这个方法调用发现服务协议    [peripheral discoverServices:nil];}//扫描到服务-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {    NSLog(@">>>扫描到服务:%@",peripheral.services);    if (error) {        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);        return;    }        for (CBService *service in [peripheral services]){        [peripheral discoverCharacteristics:nil forService:service];    }}//扫描到特征- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {        if (error) {        NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);        return;    }        for (CBCharacteristic *characteristic in service.characteristics) {                NSLog(@">>>服务:%@ 的 特征: %@",service.UUID,characteristic.UUID);                //筛选你需要的UUID,进行连接        if ([characteristic.UUID isEqual:yourUUID) {                    订阅,实时接收            [peripheral setNotifyValue:YES forCharacteristic:characteristic];        }    }}复制代码

读取数据

//获取指定特性的数据- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{    //接收蓝牙发来的数据     NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);}复制代码

写入数据

//写入数据-(void)writeData {    [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];}//写入数据的回调- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{    if (error) {         NSLog(@"error Discovered characteristics for %@ with error: %@", characteristic.UUID, [error localizedDescription]);        return;    }    NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);}复制代码

断开连接

- (void)disConnect{    [self.centralManager cancelPeripheralConnection:self.peripheral];}复制代码

转载地址:http://pveal.baihongyu.com/

你可能感兴趣的文章
使用Automake 创建和使用静态库
查看>>
Cisco交换机开启远程登录
查看>>
loganalyzer的简单使用
查看>>
SSH双向认证
查看>>
shell脚本基础
查看>>
Vert.x源码-创建集群
查看>>
wget下载整个网站
查看>>
mysql数据库迁移目录后slave报错
查看>>
Centos 7 学习之静态IP设置
查看>>
hbase内存规划(读多写少型和写多读少型)
查看>>
Web QQ 的请求交互过程
查看>>
去哪儿网——项目管理平台助力研发效率提升
查看>>
Jenkins实战演练之Linux节点任务配置
查看>>
安卓手机链接window服务器工具。安卓手机连接linux服务器工具
查看>>
应用反射技术为Infragistics Solution设计例子程序 代码简洁而且学习的效率高
查看>>
一个由C++到Java,再到Hadoop的学习历程
查看>>
JEEWX微信企业号管家,开源免费,1.0版本发布
查看>>
2018-1-10 Linux学习笔记
查看>>
echarts 去除网格
查看>>
UIScrollView、UIPageControl的练习
查看>>