最近接到新的硬件项目,需要用户手动去开启蓝牙设置。而做项目时,习惯性是调用系统的提示框。
对于我这种不太喜欢看苹果文档的人来说,有时候有点难找到相关的资料。进入正题吧。上图,上代码!
@interface HNGDevice()
@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) UIAlertController *alertC;
@end
@implementation HNGDevice
+ (instancetype)shareInstance;// 设置为单例
{
staticHNGDevice*device =nil;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
device = [[HNGDevicealloc]init];
});
returndevice;
}
- (instancetype)init
{
self= [superinit];
if(self) {
[self subPropertiesInit]; // 初始化属性
}
return self;
}
- (void)subPropertiesInit { // 初始化属性
// 初始化管理者
// CBCentralManagerOptionShowPowerAlertKey
//_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey:[NSNumber numberWithBool:NO]}];
}
#pragma mark -- CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager*)central
{
switch(central.state) {
case CBManagerStateUnknown:
NSLog(@"central.state = CBManagerStateUnknown");
break;
case CBManagerStateResetting:
{
[self showAlertViewTitle:@"Note!" message:@"Your apple device has bluetooth reset, please close the APP and reopen." rescan:NO];
NSLog(@"central.state = CBManagerStateResetting .........iPhone正在重置蓝牙");
}
break;
case CBManagerStateUnsupported:
NSLog(@"central.state = CBManagerStateUnsupported");
break;
case CBManagerStateUnauthorized:
NSLog(@"central.state = CBManagerStateUnauthorized");
break;
case CBManagerStatePoweredOff: {
NSLog(@"centralManager 未开启蓝牙..");
// 代理监控蓝牙未开启,状态改为正在扫描中
}
break;
case CBManagerStatePoweredOn:
{
NSLog(@"centralManager 已开启蓝牙..");
}
break;
}
}
如上,习惯性用第一个实例方法,这个是默认系统弹出提示框的:
当你不需要这自动提示框时,就写第二个实例方法:
(NSDictionary<NSString> *)options 把这个参数写上CBCentralManagerOptionShowPowerAlertKey 用于当中心管理类被初始化时若此时蓝牙系统为关闭状态,是否向用户显示警告对话框。该字段对应的是NSNumber类型的对象,默认值为NO,需要改成 YES。然后这样就ok,下面继续做别的处理。
网友评论