前言:一個簡單的BlueTooth管理類,直接貼代碼。
.h文件
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@protocol HSBlueToothManagerDelegate <NSObject>
@optional
/**
發現外設
@param central 中心
@param peripheral 外設
*/
- (void)blueToothManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral;
/**
連接外設成功並找到對應的特徵,這個時候就可以寫入數據
@param central 中心
@param peripheral 外設
*/
- (void)blueToothManager:(CBCentralManager *)central didDiscoverCharacteristicsFromPeripheral:(CBPeripheral *)peripheral;
@end
@interface HSBlueToothManager : NSObject
+ (HSBlueToothManager *)shareBlueToothManager;
//開始掃描設備
- (void)startScanningDevices;
//結束掃描設備
- (void)stopScanningDevices;
//開始連接
- (void)startConnectPeripheral:(CBPeripheral *)peripheral;
//寫入數據
- (void)writeString:(NSString *)string;
- (void)writeData:(NSData *)data;
//關閉連接
- (void)closeConnectPeripheral;
@property (nonatomic,weak) id<HSBlueToothManagerDelegate> delegate;
@end
#import "HSBlueToothManager.h"
//定義uuid
static NSString *const KServiceUUID = @"9830BC16-5CE7-43CD-996F-74E9110C4CEA";
static NSString *const KCharacteristicUUID = @"F6F6B7E0-897D-4F51-959F-387A94BF440E";
@interface HSBlueToothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>
//中央設備管理者
@property (nonatomic,strong) CBCentralManager *centralManager;
//外設
@property (nonatomic,strong) CBPeripheral *peripheral;
//特徵
@property (nonatomic,strong) CBCharacteristic *characteristic;
@end
@implementation HSBlueToothManager
//懶加載
- (CBCentralManager *)centralManager
{
if (!_centralManager) {
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
}
return _centralManager;
}
+ (HSBlueToothManager *)shareBlueToothManager
{
static HSBlueToothManager *shareBlueToothManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareBlueToothManager = [[self alloc] init];
});
return shareBlueToothManager;
}
#pragma mark 開始掃描設備
- (void)startScanningDevices
{
if (self.centralManager.isScanning == NO) {
//查找所有
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
}
}
#pragma mark 停止掃描設備
- (void)stopScanningDevices
{
[self.centralManager stopScan];
}
#pragma mark 開始連接
- (void)startConnectPeripheral:(CBPeripheral *)peripheral
{
//1.賦值
self.peripheral = peripheral;
//2.設置代理
self.peripheral.delegate = self;
NSDictionary *options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey];
//3.開始連接
[self.centralManager connectPeripheral:self.peripheral options:options];
}
#pragma mark 寫入數據
- (void)writeString:(NSString *)string
{
if (self.peripheral != nil) {
NSData *data = [NSData dataWithBytes:string.UTF8String length:string.length];
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithoutResponse];
}
}
- (void)writeData:(NSData *)data
{
if (self.peripheral != nil) {
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithoutResponse];
}
}
#pragma mark 關閉連接
- (void)closeConnectPeripheral
{
if (self.peripheral != nil) {
[self.centralManager cancelPeripheralConnection:self.peripheral];
}
self.peripheral = nil;
}
#pragma mark - CBCentralManagerDelegate
#pragma mark 更新狀態
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
switch (central.state) {
case CBManagerStatePoweredOn:
NSLog(@"藍牙已打開");
break;
default:
break;
}
}
#pragma mark 發現設備
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
NSLog(@"scan device:%@",peripheral.name);
if (_delegate != nil && [_delegate respondsToSelector:@selector(blueToothManager:didDiscoverPeripheral:)]) {
[_delegate blueToothManager:central didDiscoverPeripheral:peripheral];
}
}
#pragma mark 連接設備(成功)
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
//掃描外設中的服務
[peripheral discoverServices:nil];
}
#pragma mark 連接設備(失敗)
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
}
#pragma mark 斷開連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(nullable NSError *)error
{
}
#pragma mark - CBPeripheralDelegate
#pragma mark 發現服務
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
NSLog(@"掃描服務");
//獲取外設中所有掃描到的服務
if (!error) {
NSArray *services = peripheral.services;
for (CBService *service in services) {
NSLog(@"service.UUID is %@",service.UUID.UUIDString);
//判斷service.UUID是否是我們需要的
if ([service.UUID.UUIDString isEqualToString:KServiceUUID]) {
//nil表示查找所有
[peripheral discoverCharacteristics:nil forService:service];
}
}
}else {
NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
}
}
#pragma mark 發現特徵
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (!error) {
NSArray *characteristics = service.characteristics;
for (CBCharacteristic *characteristic in characteristics) {
NSLog(@"characteristic.UUID is %@",characteristic.UUID.UUIDString);
if ([characteristic.UUID.UUIDString isEqualToString:KCharacteristicUUID]) {
NSString *valueStr = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSLog(@"valueStr is %@",valueStr);
//保存特徵
self.characteristic = characteristic;
//開啓監聽,爲了保持連接
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
//執行代理
if (_delegate != nil && [_delegate respondsToSelector:@selector(blueToothManager:didDiscoverCharacteristicsFromPeripheral:)]) {
[_delegate blueToothManager:self.centralManager didDiscoverCharacteristicsFromPeripheral:peripheral];
}
}
}
}else {
NSLog(@"Discovered read characteristics:%@ for service: %@", service.UUID, service.UUID);
}
}
#pragma mark 寫入信息回調
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"寫入信息回調 is %@",error);
}
#pragma mark 寫入信息描述回調
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error
{
NSLog(@"寫入信息描述回調 peripheral:%@,descriptor:%@,error:%@",peripheral,descriptor,error);
}
#pragma mark 值發生變化的調用
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(@"值發生變化的調用 peripheral:%@,characteristic:%@,error:%@",peripheral,characteristic,error);
}
@end