做了一个单例
h文件
#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^DidRefreshPeripherals)(void);
typedef void(^CentralManagerDidUpdateState)(CBManagerState state);
typedef void(^DidConnectPeripheral)(void);
typedef void(^DidFailToConnectPeripheral)(void);
typedef void(^DidDisconnectPeripheral)(void);
typedef void(^DidDiscoverServicesErr)(NSError *err);
typedef void(^GetConnectionStatus)(NSString *connectionStatus);
typedef void(^DidReceiveMSG)(int value);
@interface BluetoothCenter : NSObject<CBCentralManagerDelegate,CBPeripheralDelegate>
@property(strong,nonatomic) CBCentralManager *centerManager;//--------中心设备管理器
@property(strong,nonatomic) NSMutableArray *peripherals;//------------所有蓝牙外设
@property(strong,nonatomic) NSDictionary *currentPeripheral;//----------当前连接的外设
@property(copy)CentralManagerDidUpdateState centralManagerDidUpdateState;
@property(copy)DidRefreshPeripherals didRefreshPeripherals;
@property(copy)DidConnectPeripheral didConnectPeripheral;
@property(copy)DidFailToConnectPeripheral didFailToConnectPeripheral;
@property(copy)DidDisconnectPeripheral didDisconnectPeripheral;
@property(copy)DidDiscoverServicesErr didDiscoverServicesErr;
@property(copy)DidReceiveMSG didReceiveMSG;
@property (nonatomic ,assign) BOOL switchStatus;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (id)copy NS_UNAVAILABLE; // 没有遵循协议可以不写
- (id)mutableCopy NS_UNAVAILABLE; // 没有遵循协议可以不写
+ (instancetype)sharedCenter;
//第四步:连接蓝牙设备
- (void)connectPeripheral:(CBPeripheral *)peripheral;
- (void)startScanPeripheral;
- (void)stopScanPeripheral;
@end
NS_ASSUME_NONNULL_END
m文件
#import "BluetoothCenter.h"
@implementation BluetoothCenter
// 跟上面的方法实现有一点不同
+ (instancetype)sharedCenter {
static BluetoothCenter *_sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 要使用self来调用
_sharedSingleton = [[self alloc] init];
[_sharedSingleton initCBCentralManager];
});
return _sharedSingleton;
}
#pragma mark ===== init =====
/*第一步:创建设备管理器
创建完之后,会回掉CBCentralManagerDelegate中的方法:- (void)centralManagerDidU