周末不想在家 2024-01-30 21:14 采纳率: 5.7%
浏览 5

ios进行蓝牙扫描必须放到ViewController中吗?

ios进行蓝牙扫描必须要放到ViewController中码?如果把代码放到一个普通类里为什么不执行centralManagerDidUpdateState回调?

在ViewController中执行代码

_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey:@NO}];

以下代码会有回调


-(void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBPeripheralManagerStatePoweredOn:
            NSLog(@"BLE已打开.");
            break;
            
        default:
            break;
    }
}

但是如果把相同的代码放到一个单独的类里centralManagerDidUpdateState方法不会有回调

  • 写回答

2条回答 默认 最新

  • 叫兽-郭老师 新星创作者: Java技术领域 2024-01-30 21:15
    关注

    参考通义千问和郭老师的小迷弟雅思莫了-编写提供,主要是为了帮助您快速解决问题,如下回答,您可以参考下,如有问题,评论区留言。

    在 iOS 中进行蓝牙扫描并不强制要求必须放在 ViewController 中,您完全可以将蓝牙相关的代码封装到一个单独的类(例如:一个遵循 CBCentralManagerDelegate 协议的类)中。之所以您在普通类里无法接收到 centralManagerDidUpdateState 回调,可能是因为以下原因:

    1. 初始化并设置代理:确保在创建 CBCentralManager 对象时正确设置了代理,并且代理对象(您的普通类实例)需要遵循 CBCentralManagerDelegate 协议。
    // 普通类(遵循 CBCentralManagerDelegate)
    @interface MyBluetoothManager : NSObject <CBCentralManagerDelegate>
    
    @property (nonatomic, strong) CBCentralManager *centralManager;
    
    - (instancetype)init;
    @end
    
    @implementation MyBluetoothManager
    
    - (instancetype)init {
        self = [super init];
        if (self) {
            _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey:@NO}];
        }
        return self;
    }
    
    // 实现 delegate 方法
    -(void)centralManagerDidUpdateState:(CBCentralManager *)central {
        switch (central.state) {
            case CBPeripheralManagerStatePoweredOn:
                NSLog(@"BLE已打开.");
                break;
            default:
                break;
        }
    }
    
    @end
    
    1. 生命周期管理:如果这个普通类没有被正确持有和释放,可能会导致中央管理者(CBCentralManager)提前被释放,从而无法接收到回调。确保在适当的地方创建并持有该类的实例。

    2. 主运行循环队列:虽然通常情况下使用主线程的队列(nil)即可正常接收回调,但如果您在其他线程初始化 CBCentralManager,可能需要显式地指定主队列(dispatch_get_main_queue())来处理回调。

    请检查以上几点,确保在普通类中正确配置 CBCentralManager 以及其代理实现。

    评论

报告相同问题?

问题事件

  • 创建了问题 1月30日