1.引入蓝牙
#import <CoreBluetooth/CoreBluetooth.h>
2.关闭提示
NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey:@(NO)};//不弹窗(配置)
[[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:options];
3.签订协议
bluetooth ()<CBCentralManagerDelegate>;
4.实现协议
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
NSString *strMessage = @"";
NSString *buttonTitle = nil;
switch (central.state) {
case CBManagerStatePoweredOn: {
NSLog(@"蓝牙开启且可用");
return;
}
break;
case CBManagerStateUnknown: {
strMessage = @"手机没有识别到蓝牙,请检查手机。";
buttonTitle = @"前往设置";
}
break;
case CBManagerStateResetting: {
strMessage = @"手机蓝牙已断开连接,重置中...";
buttonTitle = @"前往设置";
}
break;
case CBManagerStateUnsupported: {
strMessage = @"手机不支持蓝牙功能,请更换手机。";
}
break;
case CBManagerStatePoweredOff: {
strMessage = @"手机蓝牙功能关闭,请前往设置打开蓝牙及控制中心打开蓝牙。";
buttonTitle = @"前往设置";
}
break;
case CBManagerStateUnauthorized: {
strMessage = @"手机蓝牙功能没有权限,请前往设置。";
buttonTitle = @"前往设置";
}
break;
default: { }
break;
}
//通知没有打开蓝牙的自定义提示弹窗(弹窗代码自行实现)
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:strMessage preferredStyle:(UIAlertControllerStyleAlert)];
// 是否跳转到蓝牙界面()
UIAlertAction *okAction = [UIAlertAction actionWithTitle:buttonTitle style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//将字符串转换为16进制
NSData *encryptString = [[NSData alloc] initWithBytes:(unsigned char []){0x41, 0x70, 0x70, 0x2d, 0x50, 0x72, 0x65, 0x66, 0x73, 0x3a, 0x72, 0x6f, 0x6f, 0x74, 0x3d, 0x42, 0x6c, 0x75, 0x65, 0x74, 0x6f, 0x6f, 0x74, 0x68} length:24];
NSString *string = [[NSString alloc] initWithData:encryptString encoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:string];
if (@available(iOS 10.0, *)) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
} else {
[[UIApplication sharedApplication] openURL:url];
}
}];
// 创建按钮
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
网友评论