這裏只需要.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 = [[NSMutableArray alloc] init];
}
return _saveDiscountyBlueArr;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] 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.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
//實例化類並設置爲主線程
_blueManager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) options:nil];
}
#pragma mark 第一步 判斷藍牙是否可用
//掃描外部設備代理方法實現
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
switch (central.state) {
//注意,這裏手機系統如果是iOS10以上不能用CBCentralManagerStateUnknown,要用CBManagerStateUnknown,因爲在iOS10被棄用了
case CBCentralManagerStateUnknown:
[YZC_AlertView showViewWithTitleMessage:@"設備不支持"];
break;
case CBCentralManagerStateResetting:
[YZC_AlertView showViewWithTitleMessage:@"正在重置設備"];
break;
case CBCentralManagerStateUnsupported:
[YZC_AlertView showViewWithTitleMessage:@"設備不支持狀態"];
break;
case CBCentralManagerStateUnauthorized:
[YZC_AlertView showViewWithTitleMessage:@"設備未授權狀態"];
break;
case CBCentralManagerStatePoweredOff:
[YZC_AlertView showViewWithTitleMessage:@"設備關閉狀態"];
break;
case CBCentralManagerStatePoweredOn:
NSLog(@">>>CBCentralManagerStatePoweredOn");
//開始掃描周圍的外設
/*
第一個參數nil就是掃描周圍所有的外設,掃描到外設後會進入
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
*/
[_blueManager scanForPeripheralsWithServices:nil options:@{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.saveDiscountyBlueArr addObject:peripheral];
[self.tableView reloadData];
}
}
#pragma mark 第三步 點擊對應的設備進行連接
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
CBPeripheral *per = self.saveDiscountyBlueArr[indexPath.row];
//連接設備,一個主設備最多能連接7個外設,每個外設只能給一個主設備連接
self.choicePer = per;
[_blueManager connectPeripheral:per options:nil];
}
#pragma mark 第四步 連接設備成功後掃碼service
//連接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
[YZC_AlertView showTitle:nil Msg:[NSString stringWithFormat:@"連接到名稱爲(%@)的設備-成功",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, [error localizedDescription]);
return;
}
for (CBService *service in peripheral.services) {
NSLog(@"%@",service.UUID);
//掃描每個service的Characteristics,掃描到後會進入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
[peripheral discoverCharacteristics:nil forService: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, [error localizedDescription]);
return;
}
for (CBCharacteristic *characteristic in service.characteristics)
{
NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
}
//獲取Characteristic的值,讀到數據會進入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in service.characteristics){
{
[peripheral readValueForCharacteristic:characteristic];
}
}
//搜索Characteristic的Descriptors,讀到數據會進入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
for (CBCharacteristic *characteristic in 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 *d in 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:%@",[NSString stringWithFormat:@"%@",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", (unsigned long)characteristic.properties);
//只有 characteristic.properties 有write的權限纔可以寫
if(characteristic.properties & CBCharacteristicPropertyWrite){
/*
最好一個type參數可以爲CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,區別是是否會有反饋
*/
[peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}else{
NSLog(@"該字段不可寫!");
}
}
//連接到Peripherals-失敗
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
[YZC_AlertView showViewWithTitleMessage:[NSString stringWithFormat:@"連接到名稱爲(%@)的設備-失敗,原因:%@",[peripheral name],[error localizedDescription]]];
}
//Peripherals斷開連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
[YZC_AlertView showViewWithTitleMessage:[NSString stringWithFormat:@">>>外設連接斷開連接 %@: %@\n", [peripheral name], [error localizedDescription]]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.saveDiscountyBlueArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
CBPeripheral *per = self.saveDiscountyBlueArr[indexPath.row];
cell.textLabel.text = per.name;
cell.textLabel.textColor = [UIColor blackColor];
return cell;
}