所以我目前在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()
有人知道为什么这些设备似乎无法彼此连接,或者在调用之后可能没有委托函数吗?
答案 0 :(得分:0)
当静态shared
用BluetoothManager()
初始化时,该过程开始。我不确定何时在Swift中发生这种情况,是在程序的开始还是第一次使用BluetoothManager.setup
时。
变量的初始化调用init()
的{{1}}方法。这将实例化BluetoothManager
,并将调用其CentralManager
方法。这将实例化init()
,这将启动蓝牙过程。
然后您调用CBCentralManager
,它将实例化一个新的setup()
及其自己的CentralManager
。我可以想象两个CBCentralManager
出了问题。
要解决此问题,请不要使用CBCentralManager
,而应在setup()
中初始化变量。
要调试这种情况,请在所有init()
方法中放置断点。创建析构函数,并在其中也设置断点。从技术上讲,您还是需要析构函数,因为您需要将自己作为委托从init()
对象中删除。
请注意,您只能从CBCentralManager
呼叫scanForPeripherals
。 centralManagerDidUpdateState
启动时可能已经处于CBCentralManager
状态,这可能在另一个应用程序同时使用蓝牙时或您的第一个poweredOn
对象已经启动时发生。在这种情况下,CBCentralManager
将永远不会被调用。
答案 1 :(得分:0)
您确定您的Singleton已正确初始化吗?
尝试一下:
import Foundation
private let singleton = Singleton()
class Singleton {
static let sharedInstance : Singleton = {
return singleton
}()
let cnetralManager = = CBCentralManager(delegate: self, queue: DispatchQueue.main)
}