1.这个框架我已经进行了优化,提供了兼容swift的版本,并且在github上建了仓库,具体参见下面的博客
iOS(oc swift)蓝牙框架(工具类 demo)
2. .h代码
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
@protocol XXCoreBluetoothManagerDelegate
- (void)getData:(NSData*)data;
@end
#define kXXCoreBluetoothManager [XXCoreBluetoothManager shareInstance]
@interface XXCoreBluetoothManager : NSObject
@property(nonatomic,weak)id<XXCoreBluetoothManagerDelegate>delegate;
@property(nonatomic,strong)NSMutableArray <CBPeripheral *>* scanArr;
@property(nonatomic,strong)CBPeripheral *peripheral;
@property(nonatomic,strong)CBCharacteristic *characteristic;
@property(nonatomic,strong)NSString *UUIDStr;
+ (instancetype)shareInstance;
@property(nonatomic,assign)BOOL isConnected;
- (BOOL)isBluetoothAvailabel;
@property(nonatomic,strong)NSTimer *myTimer;
- (void)startScan: (void(^)(CBPeripheral *))update;
- (void)connectPeripheral:(CBPeripheral*)peripheral Completion:(void(^)(BOOL,NSError*))completion;
- (void)disconnect;
- (void)writeDataWithCharacteristic:(CBCharacteristic *)characteristic Data:(NSData *)data Completion:(void(^)(BOOL,NSError*))completion;
- (NSData *)convertHexStrToData:(NSString *)str;
- (NSString *)convertDataToHexStr:(NSData *)data;
@end
3. .m代码
#import "XXCoreBluetoothManager.h"
#import "blueTooth-Swift.h"
@interface XXCoreBluetoothManager ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property(nonatomic,copy)void(^scanBlock)(CBPeripheral *);
@property(nonatomic,copy)void(^connectBlock)(BOOL,NSError*);
@property(nonatomic,copy)void(^writeBlock)(BOOL,NSError*);
@property(nonatomic,strong)CBCentralManager *cbCentralManager;
@end
@implementation XXCoreBluetoothManager
+ (instancetype)shareInstance{
static XXCoreBluetoothManager *manager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [[XXCoreBluetoothManager alloc] init];
NSLog(@"赋值");
});
return manager;
}
- (instancetype)init{
self = [super init];
self.scanArr = [NSMutableArray new];
[self isBluetoothAvailabel];
return self;
}
-(CBCentralManager *)cbCentralManager{
if (_cbCentralManager == nil) {
self.cbCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
return _cbCentralManager;
}
- (BOOL)isBluetoothAvailabel{
BOOL flag = NO;
switch (self.cbCentralManager.state) {
case CBManagerStateUnknown:
NSLog(@"未知状态");
flag = YES;
break;
case CBManagerStateResetting:
NSLog(@"连接断开 即将重置");
break;
case CBManagerStateUnsupported:
NSLog(@"当前设备不支持蓝牙");
break;
case CBManagerStateUnauthorized:
NSLog(@"未授权");
break;
case CBManagerStatePoweredOff:
NSLog(@"蓝牙未开启");
break;
case CBManagerStatePoweredOn:
NSLog(@"蓝牙可用");
flag = YES;
break;
}
return flag;
}
- (void)startScan: (void(^)(CBPeripheral *))update{
NSAssert([self isBluetoothAvailabel], @"请检查你的蓝牙设置");
#pragma mark - 第一步 扫描外设 scanForPeripherals
[self.cbCentralManager scanForPeripheralsWithServices:nil options:nil];
self.scanBlock = update;
}
#pragma mark CBCentralManagerDelegate 蓝牙中心的代理方法
-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
NSLog(@"%zd",central.state);
}
#pragma mark - 第二步 发现外设(锁定外设)
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI{
if( [peripheral.name containsString:@"BBL"] || [peripheral.name containsString:@"SPP"] || [peripheral.name containsString:@"BLE SPS"]){
}else{
return;
}
if (![_scanArr containsObject:peripheral]) {
[_scanArr addObject:peripheral];
self.scanBlock(peripheral);
}
}
#pragma mark - 第三步 连接外设
- (void)disconnect{
[self.cbCentralManager cancelPeripheralConnection:self.peripheral];
}
- (void)connectPeripheral:(CBPeripheral*)peripheral Completion:(void(^)(BOOL,NSError*))completion{
self.connectBlock = completion;
[self.cbCentralManager connectPeripheral:peripheral options:nil];
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral{
NSLog(@"外设连接成功");
self.UUIDStr = @"FEE1";
if (self.characteristic) {
NSLog(@"进来了");
}
self.peripheral = peripheral;
self.peripheral.delegate = self;
#pragma mark - 第四步 寻找外设的服务
[self.peripheral discoverServices:nil];
}
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
NSLog(@"外设连接失败");
self.connectBlock(NO, error);
}
-(void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
NSLog(@"外设断开");
self.isConnected = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:@"peripheralCut" object:nil];
}
#pragma mark - CBPeripheralDelegate 外设的代理
- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error{
}
#pragma mark 第四步 外设发现了服务
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
#pragma mark 第五步 寻找服务的特征
for (CBService *service in peripheral.services) {
[self.peripheral discoverCharacteristics:nil forService:service];
}
}
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
for (CBCharacteristic *c in service.characteristics) {
if ([[c.UUID UUIDString] isEqualToString:self.UUIDStr]) {
NSLog(@"%@",self.UUIDStr);
self.characteristic = c;
NSLog(@"确定特征开始接收数据");
[self.peripheral setNotifyValue:YES forCharacteristic:self.characteristic];
}
}
}
#pragma mark 第六步 - 给外设的特征发送数据
- (void)writeDataWithCharacteristic:(CBCharacteristic *)characteristic Data:(NSData *)data Completion:(void(^)(BOOL,NSError*))completion{
self.writeBlock = completion;
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
[self.delegate getData:characteristic.value];
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValujeForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSLog(@"发数据成功");
if (error) {
self.writeBlock(NO, error);
}else{
self.writeBlock(YES, nil);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
NSLog(@"//以通知的形式接收外设的数据");
cameraBlueTooth *blue = [cameraBlueTooth getSharedInstance];
blue.isCameraInfo = YES;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[blue getSystemStatus];
self.isConnected = YES;
self.connectBlock(YES, nil);
});
}
- (NSData *)convertHexStrToData:(NSString *)str {
if (!str || [str length] == 0) {
return nil;
}
NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
NSRange range;
if ([str length] % 2 == 0) {
range = NSMakeRange(0, 2);
} else {
range = NSMakeRange(0, 1);
}
for (NSInteger i = range.location; i < [str length]; i += 2) {
unsigned int anInt;
NSString *hexCharStr = [str substringWithRange:range];
NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
[scanner scanHexInt:&anInt];
NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
[hexData appendData:entity];
range.location += range.length;
range.length = 2;
}
return hexData;
}
- (NSString *)convertDataToHexStr:(NSData *)data {
if (!data || [data length] == 0) {
return @"";
}
NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
unsigned char *dataBytes = (unsigned char*)bytes;
for (NSInteger i = 0; i < byteRange.length; i++) {
NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
if ([hexStr length] == 2) {
[string appendString:hexStr];
} else {
[string appendFormat:@"0%@", hexStr];
}
}
}];
return string;
}
@end
4.csdn下载
蓝牙self.zip
5.github上获得星星数最多的ios蓝牙框架:
coolnameismy/BabyBluetooth