iOS开发 蓝牙连接

来源:互联网 发布:淘宝衣服缩水美女视频 编辑:程序博客网 时间:2024/05/16 15:17

这里只需要.m文件,只做了连接蓝牙和扫描蓝牙数据

直接上代码:

//

//  FirstViewController.m

//  test

//

//  Created by HandsomeC on 2017/11/30.

//  Copyright © 2017年 赵发生. All rights reserved.

//


#import "FirstViewController.h"

#import "SecondViewController.h"

#import <CoreBluetooth/CoreBluetooth.h>

#import "YZC_AlertView.h"

#define IS_IOS_10 (([[[[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."] objectAtIndex:0] intValue] >=10) ? YES : NO)

@interface FirstViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>


@property (nonatomic,strong) CBCentralManager *blueManager;//系统的蓝牙,用它扫描设备和链接设备

@property (nonatomic,strong) NSMutableArray *saveDiscountyBlueArr;//保存扫描到的蓝牙设备

@property (nonatomic,strong) CBPeripheral *choicePer;

@end


@implementation FirstViewController


- (NSMutableArray *)saveDiscountyBlueArr{

if (_saveDiscountyBlueArr ==nil) {

_saveDiscountyBlueArr = [[NSMutableArrayalloc] init];

}

return_saveDiscountyBlueArr;

}


- (void)viewDidLoad {

    [superviewDidLoad];

self.tableView = [[UITableViewalloc] initWithFrame:CGRectMake(0,64, self.view.frame.size.width,self.view.frame.size.height-64)style:UITableViewStylePlain];

self.tableView.dataSource =self;

self.tableView.delegate =self;

self.tableView.rowHeight =50;

[self.tableViewregisterClass:[UITableViewCellclass] forCellReuseIdentifier:@"cell"];

//实例化类并设置为主线程

_blueManager = [[CBCentralManageralloc]initWithDelegate:selfqueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0) options:nil];

}


#pragma mark 第一步   判断蓝牙是否可用


//扫描外部设备代理方法实现

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{

switch (central.state) {

//注意,这里手机系统如果是iOS10以上不能用CBCentralManagerStateUnknown,要用CBManagerStateUnknown,因为在iOS10被弃用了

caseCBCentralManagerStateUnknown:

[YZC_AlertViewshowViewWithTitleMessage:@"设备不支持"];

break;

caseCBCentralManagerStateResetting:

[YZC_AlertViewshowViewWithTitleMessage:@"正在重置设备"];

break;

caseCBCentralManagerStateUnsupported:

[YZC_AlertViewshowViewWithTitleMessage:@"设备不支持状态"];

break;

caseCBCentralManagerStateUnauthorized:

[YZC_AlertViewshowViewWithTitleMessage:@"设备未授权状态"];

break;

caseCBCentralManagerStatePoweredOff:

[YZC_AlertViewshowViewWithTitleMessage:@"设备关闭状态"];

break;

caseCBCentralManagerStatePoweredOn:

NSLog(@">>>CBCentralManagerStatePoweredOn");

//开始扫描周围的外设

/*

 

第一个参数nil就是扫描周围所有的外设,扫描到外设后会进入

 

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

 

*/

[_blueManagerscanForPeripheralsWithServices:niloptions:@{CBCentralManagerRestoredStateScanOptionsKey:@(YES)}];

break;

default:

break;

}

}

#pragma mark 第二步   扫描可连接设备

//扫描到设备后进入的方法

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{

//如果没有设备,可以下载一个app,lightBlue作为调试

//这里面扫描到后可以进行连接

NSLog(@"扫描到蓝牙设备:%@",peripheral.name);

if (peripheral && peripheral.name.length) {

[self.saveDiscountyBlueArraddObject:peripheral];

[self.tableViewreloadData];

}

}


#pragma mark 第三步   点击对应的设备进行连接

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

CBPeripheral *per =self.saveDiscountyBlueArr[indexPath.row];

//连接设备,一个主设备最多能连接7个外设,每个外设只能给一个主设备连接

self.choicePer = per;

[_blueManagerconnectPeripheral:per options:nil];

}



#pragma mark 第四步   连接设备成功后扫码service

//连接到Peripherals-成功

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


{


[YZC_AlertViewshowTitle:nilMsg:[NSStringstringWithFormat:@"连接到名称为(%@)的设备-成功",peripheral.name]];

//连接成功后可以扫描服务数据

//设置代理

[peripheral setDelegate:self];

[peripheral discoverServices:nil];

//扫描外设的服务成功后会进入下面方法

}



#pragma mark 第五步   扫描service成功后扫码Characteristics

//扫描外设servis成功后可以获取设备的services

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

  NSLog(@">>>扫描到服务:%@",peripheral.services);

if (error)

{

NSLog(@">>>扫描出错 %@ 出错原因: %@", peripheral.name, [errorlocalizedDescription]);

return;

}

for (CBService *servicein peripheral.services) {

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

//扫描每个service的Characteristics,扫描到后会进入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

[peripheral discoverCharacteristics:nilforService:service];

}

}



#pragma mark 第六步   获取外设的Characteristics,获取Characteristics的值,获取Characteristics的Descriptor和Descriptor的值

//扫描到Characteristics


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

if (error)

{

NSLog(@"Characteristics扫码出错 %@ 原因: %@", service.UUID, [errorlocalizedDescription]);

return;

}

for (CBCharacteristic *characteristicin service.characteristics)

{

NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);

}

//获取Characteristic的值,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

for (CBCharacteristic *characteristicin service.characteristics){

{

[peripheral readValueForCharacteristic:characteristic];

}

}

//搜索Characteristic的Descriptors,读到数据会进入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error

for (CBCharacteristic *characteristicin service.characteristics){

[peripheral discoverDescriptorsForCharacteristic:characteristic];

}

}


#pragma mark 第七步 获取的charateristic的值

//获取的charateristic的值


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

//打印出characteristic的UUID和值

//!注意,value的类型是NSData,具体开发时,会根据外设协议制定的方式去解析数据

NSLog(@"获取的charateristic的值 characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);


}


#pragma mark 第八 步 搜索到Characteristic的Descriptors


//搜索到Characteristic的Descriptors


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

//打印出Characteristic和他的Descriptors

NSLog(@"characteristic uuid:%@",characteristic.UUID);

for (CBDescriptor *din characteristic.descriptors) {

NSLog(@"搜索到Characteristic的Descriptors Descriptor uuid:%@",d.UUID);

}

}


//获取到Descriptors的值


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

//打印出DescriptorsUUID 和value

//这个descriptor都是对于characteristic的描述,一般都是字符串,所以这里我们转换成字符串去解析

NSLog(@" 获取到Descriptors的值 characteristic uuid:%@  value:%@",[NSStringstringWithFormat:@"%@",descriptor.UUID],descriptor.value);

}


#pragma mark 第九步 把数据写到Characteristic中

//写数据


-(void)writeCharacteristic:(CBPeripheral *)peripheral


characteristic:(CBCharacteristic *)characteristic


value:(NSData *)value{

//打印出 characteristic 的权限,可以看到有很多种,这是一个NS_OPTIONS,就是可以同时用于好几个值,常见的有read,write,notify,indicate,知知道这几个基本就够用了,前连个是读写权限,后两个都是通知,两种不同的通知方式。

/*

 

typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {

 

CBCharacteristicPropertyBroadcast = 0x01,

 

CBCharacteristicPropertyRead = 0x02,

 

CBCharacteristicPropertyWriteWithoutResponse = 0x04,

 

CBCharacteristicPropertyWrite = 0x08,

 

CBCharacteristicPropertyNotify = 0x10,

 

CBCharacteristicPropertyIndicate = 0x20,

 

CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,

 

CBCharacteristicPropertyExtendedProperties = 0x80,

 

CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x100,

 

CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0) = 0x200

 

};

 

 

 

*/

NSLog(@"%lu", (unsignedlong)characteristic.properties);

//只有 characteristic.properties 有write的权限才可以写

if(characteristic.properties &CBCharacteristicPropertyWrite){

/*

 

最好一个type参数可以为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈

 

*/

[peripheral writeValue:value forCharacteristic:characteristictype:CBCharacteristicWriteWithResponse];

}else{

NSLog(@"该字段不可写!");

}

}



//连接到Peripherals-失败

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


{

[YZC_AlertViewshowViewWithTitleMessage:[NSStringstringWithFormat:@"连接到名称为(%@)的设备-失败,原因:%@",[peripheral name],[errorlocalizedDescription]]];

}

//Peripherals断开连接


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

[YZC_AlertViewshowViewWithTitleMessage:[NSStringstringWithFormat:@">>>外设连接断开连接 %@: %@\n", [peripheral name], [errorlocalizedDescription]]];

}



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

returnself.saveDiscountyBlueArr.count;

}


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

UITableViewCell *cell = [tableViewdequeueReusableCellWithIdentifier:@"cell"];

CBPeripheral *per =self.saveDiscountyBlueArr[indexPath.row];

cell.textLabel.text = per.name;

cell.textLabel.textColor = [UIColorblackColor];

return cell;

}


原创粉丝点击