CoreBluetooth功能不适用于Singleton

问题描述 投票:2回答:2

所以我目前在iPad和iPhone之间建立了蓝牙连接。我在ViewController创建了我的测试代码,一切正常。现在我将它移动到2个管理器类,一个用于CBCentralManager,一个用于CBPeripheralManager,高于那些类,我做了一个BluetoothManager,这是一个单例类,并保存有关当前连接设备的一些信息。

然而,当这样做我面临一个问题,似乎centralManager.connect()呼叫实际上没有工作。我调试了我的整个代码,在那之后似乎没有任何事情发生,我似乎无法弄清楚为什么这是或我实际上出错了。

CentralManager类

import Foundation
import CoreBluetooth

class CentralManager: NSObject {
    private var centralManager: CBCentralManager!
    var peripherals: [CBPeripheral] = []

    override init() {
        super.init()

        centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
    }
}

// MARK: - CBCentralManager Delegate Methods
extension CentralManager: CBCentralManagerDelegate {

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            centralManager.scanForPeripherals(withServices: [BLEConstants.serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
        default:
            break
        }
    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if !peripherals.contains(peripheral) {
            peripheral.delegate = self
            peripherals.append(peripheral)
            centralManager.connect(peripheral, options: nil)
        }
    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.discoverServices([BLEConstants.serviceUUID])
    }

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        guard let peripheralIndex = peripherals.index(of: peripheral), BluetoothManager.shared.deviceCharacteristic[peripheral] != nil else { return }

        peripherals.remove(at: peripheralIndex)
        BluetoothManager.shared.deviceCharacteristic.removeValue(forKey: peripheral)
    }

}

// MARK: - CBPeripheral Delegate Methods
extension CentralManager: CBPeripheralDelegate {

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        for service in peripheral.services! {
            if service.uuid == BLEConstants.serviceUUID {
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        for characteristic in service.characteristics! {
            let characteristic = characteristic as CBCharacteristic

            if BluetoothManager.shared.deviceCharacteristic[peripheral] == nil {
                BluetoothManager.shared.deviceCharacteristic[peripheral] = characteristic
            }
        }
    }

    func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {

    }

}

PeripheralManager类

class PeripheralManager: NSObject {
    private var peripheralManager: CBPeripheralManager!

    override init() {
        super.init()

        peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    }

}

// MARK: - Manage Methods
extension PeripheralManager {

    func updateAdvertising() {
        guard !peripheralManager.isAdvertising else { peripheralManager.stopAdvertising(); return }

        let advertisingData: [String: Any] = [CBAdvertisementDataServiceUUIDsKey: BLEConstants.serviceUUID,
                               CBAdvertisementDataLocalNameKey: BLEConstants.bleAdvertisementKey]
        peripheralManager.startAdvertising(advertisingData)
    }

    func initializeService() {
        let service = CBMutableService(type: BLEConstants.serviceUUID, primary: true)

        let characteristic = CBMutableCharacteristic(type: BLEConstants.charUUID, properties: BLEConstants.charProperties, value: nil, permissions: BLEConstants.charPermissions)
        service.characteristics = [characteristic]

        peripheralManager.add(service)
    }

}

// MARK: - CBPeripheralManager Delegate Methods
extension PeripheralManager: CBPeripheralManagerDelegate {

    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            initializeService()
            updateAdvertising()
        }
    }

    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        for request in requests {
            if let value = request.value {
                let messageText = String(data: value, encoding: String.Encoding.utf8)
                print(messageText ?? "")
            }
            self.peripheralManager.respond(to: request, withResult: .success)
        }
    }

}

BluetoothManager类

class BluetoothManager {
    static let shared = BluetoothManager()
    private var centralManager: CentralManager!
    private var peripheralManager: PeripheralManager!

    var deviceCharacteristic: [CBPeripheral: CBCharacteristic] = [:]
    var connectedPeripherals: [CBPeripheral] { return centralManager.peripherals }

    func setup() {
        centralManager = CentralManager()
        peripheralManager = PeripheralManager()
    }

}

然后在我的ViewController didLoad我打电话给BluetoothManager.shared.setup()

有谁知道为什么这些设备似乎没有相互连接或者之后的代理功能只是不被调用?

ios swift bluetooth-lowenergy core-bluetooth
2个回答
0
投票

当使用shared初始化静态BluetoothManager()变量时,该过程开始。我不确定Swift中是否会发生这种情况,或者是在程序的最开始,或者是第一次使用BluetoothManager.setup时。变量的初始化调用init()BluetoothManager方法。这将实例化CentralManager,并将调用其init()方法。这将实例化一个CBCentralManager,它将启动蓝牙过程。

然后你调用setup(),它将使用自己的CentralManager实例化一个新的CBCentralManager。我可以想象两个CBCentralManager出了问题。

要解决它,不要使用setup(),而是在init()中初始化变量。

要调试这种情况,请在所有init()方法中放置断点。创建析构函数,并在这些中添加断点。从技术上讲,无论如何都需要析构函数,因为你需要从CBCentralManager对象中删除自己作为委托。


另请注意,您只能从scanForPeripherals调用centralManagerDidUpdateStateCBCentralManager在启动时已经处于poweredOn状态,这可能发生在另一个应用程序同时使用蓝牙时 - 或者当您的第一个CBCentralManager对象已经启动它时。在那种情况下,centralManagerDidUpdateState永远不会被召唤。


0
投票

你确定你的Singleton被正确初始化了吗?

试试这个:

import Foundation

private let singleton = Singleton()

class Singleton {

  static let sharedInstance : Singleton = {
    return singleton
  }()

  let cnetralManager = = CBCentralManager(delegate: self, queue: DispatchQueue.main)
}
© www.soinside.com 2019 - 2024. All rights reserved.