iOS中蓝牙的使用
Core Bluetooth的使用
1,建立中心设备
2,扫描外设(Discover Peripheral)
3,连接外设(Connect Peripheral)
4,扫描外设中的服务和特征(Discover Services And Characteristics)
5,利用特征与外设做数据交互(Explore And Interact)
6,断开连接(Disconnect)
// ViewController.m
// 01-蓝牙4.0
// Created by apple on 16/1/4.
// Copyright © 2016年 apple. All rights reserved.
#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic,strong)CBCentralManager *manager;
@property (nonatomic,strong)NSMutableArray *peripherals;//盛放外围设备的数组
@end
@implementation ViewController
- (NSMutableArray *)peripherals
{
if (_peripherals == nil) {
_peripherals = [NSMutableArray array];
}
return _peripherals;
}
- (void)viewDidLoad {
[super viewDidLoad];
//1.创建中心管理者
//传 nil 为主队列
CBCentralManager *manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
self.manager = manager;
}
//状态发生改变的时候 回来到此方法
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
//2.先判断蓝牙是打开
if (central.state == CBCentralManagerStatePoweredOn) {
//3.搜索外围设备
[central scanForPeripheralsWithServices:nil options:nil];
}
}
//CBPeripheral 外围设备
//advertisementData配置信息
//RSSI 信号强度
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
[self.peripherals addObject:peripheral];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//4.连接外围设备
//遍历数组
for (int i = 0; i < self.peripherals.count; i ++) {
CBPeripheral *peripheral = self.peripherals[i];
[self.manager connectPeripheral:peripheral options:nil];
}
}
//连接外围设备之后 会来到此方法
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
//5.获取服务
[peripheral discoverServices:nil];
peripheral.delegate = self;
}
//发现服务会来的此方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
//6.通过服务去找特征
[peripheral discoverCharacteristics:nil forService:peripheral.services.lastObject];
}
//发现特征会来的此方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
}
@end
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix