iOS蓝牙--CoreBluetooth基本使用

蓝牙使用步骤:

1. 扫描外设

2. 连接外设

3. 连上外设后,获取指定外设的服务

4. 获取服务后,遍历服务的特征,得到可读,可写等特征,然后与中心管理者进行数据交互

附上代码

一:导入框架

#import <CoreBluetooth/CoreBluetooth.h>

#import <CoreLocation/CoreLocation.h>

二:设置代理,以及属性

<CBCentralManagerDelegate, CBPeripheralDelegate, UITableViewDataSource, UITableViewDelegate,CLLocationManagerDelegate>

/**

*  外设数组

*/

@property (nonatomic, strong) NSMutableArray *peripherals;

/**

*  中心管理者

*/

@property (nonatomic, strong) CBCentralManager *mgr;

/*

*   展示数据

*/

@property (nonatomic, strong) UITableView *tableView;

// 外设

@property (nonatomic, strong) CBPeripheral *peripheral;

// 特征

@property (nonatomic, strong) CBCharacteristic *characteristic;

三:方法实现

//懒加载 重写getter方法

- (NSMutableArray *)peripherals

{

if (!_peripherals) {

_peripherals = [NSMutableArray array];

}

return _peripherals;

}

- (void)viewDidLoad

{

[super viewDidLoad];

UIBarButtonItem *buttonI = [[UIBarButtonItem alloc] initWithTitle:@"扫描" style:UIBarButtonItemStylePlain target:self action:@selector(openOrclosed)];

self.navigationItem.rightBarButtonItem = buttonI;

UIBarButtonItem *buttonRB = [[UIBarButtonItem alloc] initWithTitle:@"open" style:UIBarButtonItemStylePlain target:self action:@selector(openTheDoor)];

self.navigationItem.leftBarButtonItem = buttonRB;

self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];

[self.view addSubview:self.tableView];

self.tableView.delegate = self;

self.tableView.dataSource = self;

// Do any additional setup after loading the view.

}

#pragma mark - CBCentralManagerDelegate

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

{

// 保存扫描到得外部设备

// 判断如果数组中不包含当前扫描到得外部设置才保存

NSLog(@"查找设备");

if (![self.peripherals containsObject:peripheral]) {

//        if ([peripheral.identifier.UUIDString isEqualToString:@""]) {

[self.peripherals addObject:peripheral];

//        peripheral.delegate = self;

[self.tableView reloadData];

//        }

}

}

#pragma mark 显示数据的tableView的代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

return self.peripherals.count;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

return 1;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *cell_id = @"cell_id";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];

if (cell == nil) {

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cell_id];

}

CBPeripheral *peripheral = self.peripherals[indexPath.row];

cell.textLabel.text = peripheral.name;

return cell;

}

#pragma mark tableView的点击事件

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

//    self.peripheral = self.peripherals[indexPath.row];

//    self.peripheral.delegate = self;

//    ((CBPeripheral *)self.peripherals[indexPath.row]).delegate=self;

//    [self.mgr connectPeripheral:self.peripherals[indexPath.row] options:nil];

self.peripheral = self.peripherals[indexPath.row];

[self.mgr connectPeripheral:self.peripheral options:nil];

self.peripheral.delegate = self;

//    ((CBPeripheral *)self.peripherals[indexPath.row]).delegate=self;

}

/**

*  扫描外设

*/

- (void)openOrclosed

{

if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"扫描"]) {

NSLog(@"扫描");

[self.navigationItem.rightBarButtonItem setTitle:@"断开"];

// 1.创建中心设备

// 设置代理

self.mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

// 2.利用中心设备扫描外部设备

/*

如果指定数组代表只扫描指定的设备

*/

[self.mgr scanForPeripheralsWithServices:nil options:nil];

} else {

NSLog(@"断开");

[self.mgr stopScan];

if (self.peripheral != nil)

{

NSLog(@"disConnect start");

[self.mgr cancelPeripheralConnection:self.peripheral];

}

self.peripherals = nil;

[self.tableView reloadData];

[self.navigationItem.rightBarButtonItem setTitle:@"扫描"];

}

}

/**

*  连接外设成功调用

*/

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

{

//    [self showTheAlertViewWithMassage:@"链接成功"];

NSLog(@"链接成功");

// 扫描外设中得服务

[peripheral discoverServices:nil];

}

/**

*  连接外设失败调用

*/

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

{

//    [self showTheAlertViewWithMassage:@"链接失败"];

NSLog(@"链接失败");

}

#pragma makr - CBPeripheralDelegate

/**

*  只要扫描到服务就会调用

*

*  @param peripheral 服务所在的外设

*/

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

{

NSLog(@"扫描服务");

//    [self showTheAlertViewWithMassage:@"扫描服务"];

// 获取外设中所有扫描到得服务

NSArray *services = peripheral.services;

for (CBService *service in services) {

// 拿到需要的服务

NSLog(@"%@", service.UUID.UUIDString);

if ([service.UUID.UUIDString isEqualToString:RX_SERVICE_UUID])

{

[self showTheAlertViewWithMassage:@"拿到了对应的服务了"];

// 从需要的服务中查找需要的特征

// 从peripheral中得service中扫描特征

[peripheral discoverCharacteristics:nil forService:service];

}

}

}

/**

*  只要扫描到特征就会调用

*

*  @param peripheral 特征所属的外设

*  @param service    特征所属的服务

*/

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

{

NSLog(@"扫描特征");

// 拿到服务中所有的特征

NSArray *characteristics =  service.characteristics;

// 遍历特征, 拿到需要的特征处理

for (CBCharacteristic * characteristic in characteristics) {

if ([characteristic.UUID.UUIDString isEqualToString:RX_CHAR_UUID]) {

//            [self showTheAlertViewWithMassage:@"拿到只读的的特征了"];

NSLog(@"拿到可写的的特征了");

//            characteristic.value

NSString *valueStr = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];

NSLog(@"%@????", valueStr);

self.characteristic = characteristic;

[self showTheAlertViewWithMassage:valueStr];

}

if ([characteristic.UUID.UUIDString isEqualToString:TX_CHAR_UUID]) {

}

}

}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central

{

NSLog(@"检测代理方法");

if (central.state == 5) {

[self.mgr scanForPeripheralsWithServices:nil options:nil];

//        [self showTheAlertViewWithMassage:@"手机蓝牙处于可用状态"];

}

NSLog(@"%ld, %@", central.state, central);

}

#pragma mark 发送消息成功

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

{

NSLog(@"发送消息的回调");

NSLog(@"----%@", error);

if (!error) {

NSLog(@"??????????");

}

}

#pragma mark 处理蓝牙发送过来的数据

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error

{

NSLog(@"接收到数据");

}

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

{

NSLog(@">>>>>>>");

if (error)

{

NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);

//        if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadError:)])

//            [_mainMenuDelegate DidNotifyReadError:error];

//

//        return;

}

NSMutableData *recvData;

[recvData appendData:characteristic.value];

if ([recvData length] >= 5)//已收到长度

{

unsigned char *buffer = (unsigned char *)[recvData bytes];

int nLen = buffer[3]*256 + buffer[4];

if ([recvData length] == (nLen+3+2+2))

{

//接收完毕,通知代理做事

//            if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadData)])

//                [_mainMenuDelegate DidNotifyReadData];

NSLog(@"???????");

}

}

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

- (void)showTheAlertViewWithMassage:(NSString *)massage

{

UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:massage delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];

[alertV show];

}

- (void)openTheDoor

{

NSLog(@"拿到了可读可写的特征了");

//    self.peripheral.delegate = self;

//    characteristic.value = [string dataUsingEncoding:NSUTF8StringEncoding];

//    characteristic.value = [NSData dataWithBytes:string.UTF8String length:string.length];

//    [self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];

//    [self.peripheral setNotifyValue:NO forCharacteristic:self.characteristic];

[self writeString:@"OLWANDA_IL12345678"];

}

- (void) writeString:(NSString *) string

{

NSData *data = [NSData dataWithBytes:string.UTF8String length:string.length];

//       NSLog(@"%@",self.characteristic.UUID.UUIDString);

self.peripheral.delegate=self;

NSLog(@"%@",self.peripheral.delegate);

if ((self.characteristic.properties & CBCharacteristicPropertyWriteWithoutResponse) != 0)

{

[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithoutResponse];

}

else if ((self.characteristic.properties & CBCharacteristicPropertyWrite) != 0)

{

[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];

}

else

{

NSLog(@"No write property on TX characteristic, %ld.", self.characteristic.properties);

}

//    <CBCharacteristic: 0x17408f500, UUID = 6E400002-B5A3-F393-E0A9-E50E24DCCA9E, properties = 0xC, value = (null), notifying = NO>

}

时间: 2024-11-08 08:15:15

iOS蓝牙--CoreBluetooth基本使用的相关文章

关于iOS蓝牙开发二三事

iOS蓝牙极速开发 一.背景 最近一段时间,由于公司一套蓝牙设备更新,通讯协议上需要修改,功能也要完善,因此需要更新app.坑爹的是,这款app开发到现在已有一年时间,出了源码和app啥都没有.无奈,上级交与的任务难也要做.花了大概三天时间熟悉整个项目,由于app的主要功能在于与公司的配套设备进行交互,所以,界面上的东西我就一带而过,主要了解蓝牙交互的内容. 经过仔细了解,我发现这款app的开发者也是极品,不知道是不了解C的基本知识,还是不会用,整个蓝牙交互的数据全部使用字符串操作,这对一个开发

https://github.com/coolnameismy/BabyBluetooth github上的一个ios 蓝牙4.0的库并带文档和教程

The easiest way to use Bluetooth (BLE )in ios,even bady can use. 简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和mac osx. 为什么使用它? 1:基于原生CoreBluetooth框架封装的轻量级的开源库,可以帮你更简单地使用CoreBluetooth API. 2:CoreBluetooth所有方法都是通过委托完成,代码冗余且顺序凌乱.BabyBluetooth使用block方法,可以重新按照功能和顺序

iOS 蓝牙4.0相关资料

推酷资料 http://www.tuicool.com/topics/10200246 日本的一个技术博客 http://see.sl088.com/wiki/蓝牙4.0_For_IOS#cite_note-7 http://lynchwong.com http://lynchwong.com/2014/12/15/iOS蓝牙,CoreBluetooth框架简介及入门使用/

iOS蓝牙开发(一)蓝牙相关基础知识

原文链接: http://liuyanwei.jumppo.com/2015/07/17/ios-BLE-1.html iOS蓝牙开发(一)蓝牙相关基础知识: 蓝牙常见名称和缩写 MFI ======= make for ipad ,iphone, itouch 专们为苹果设备制作的设备 BLE ==== buletouch low energy,蓝牙4.0设备因为低耗电,所以也叫做BLE peripheral,central == 外设和中心,发起连接的时central,被连接的设备为peri

IOS蓝牙开发

IOS蓝牙开发 http://blog.csdn.net/xufeidll/article/details/24022261 http://blog.csdn.net/swibyn/article/details/20531593 由于接到iphone需要和第三方蓝牙设备交互的任务,便开始了蓝牙开发这件事. 在探索了一段时间后,iOS的蓝牙开发相关Apple大致有以下几种方式. 1 GameKit.framework [只能存在于iOS设备之间,多用于游戏 能搜索到的demo比较多,不确切说名字

iOS蓝牙开发框架

iOS支持了蓝牙4.0后,很多智能硬件开始通过蓝牙与手机进行通讯互交,比如蓝牙秤,各种蓝牙医疗设备等.每个设备有不同的型号,且不断迭代更新,软件如何支持多种设备,如何区分多个设备,并分别对不同的设备进行控制,我给大家分享一个我总结的蓝牙开发框架. 核心蓝牙控制采用iOS自带的CoreBluetooth,本身该库已经可以很好的操控蓝牙设备,我的框架也仅仅是对该库的进一步封装,目的是解决如下几个问题1 区分多个设备的连接状态2 多个设备各自的蓝牙通信处理 我的蓝牙框架将设备连接,设备使能通道开启,设

(转)iOS蓝牙调用的一般流程

文章转自:http://www.cnblogs.com/ctaodream/archive/2013/07/03/3169962.html 一.服务端(也叫周边设备吧..脑残的翻译) 1.实现类必须遵守协议 CBPeripheralManagerDelegate 2.需要的主要类有: @property(strong,nonatomic) CBPeripheralManager *peripheraManager; @property(strong,nonatomic) CBMutableCha

iOS蓝牙编程指南 -- 核心蓝牙概述

小引 随着穿戴设备和智能家居的热情不断,app蓝牙的开发也很火热,基于iOS蓝牙的开发资料有不少,但是最最值得学习的必然是apple自家的文档啦,我之前的项目基于蓝牙4.0,开发过程中用到Core Bluetooth框架,算是我学习的笔记吧!涉及到几个部分,我打算分开把他们整理出来,本篇文章通过对Core Bluetooth Programming Guide的翻译,为大家介绍iOS蓝牙4.0编程的一些术语和概念,后续文章将会简单介绍下代码的流程.本人实力有限,了解的深度不是很广,还请各位看官轻

iOS蓝牙APP常驻后台

iOS蓝牙类APP常驻后台的实现方法,经过在苹果开发者论坛询问,以及查看苹果开发者文档,最后得出正确的方法为: 1.设置plist,蓝牙权限 2.到target-capabilities-background modes中打开use Bluetooth LE accessories选项 3.创建central manager时设置restore identifier _bluetoothmanager = [[CBCentralManager alloc] initWithDelegate:se