ios - CoreBluetooth 功能在 Singleton 中不起作用
<p><p>所以我目前在 iPad 和 iPhone 之间设置了蓝牙连接。我在 <code>ViewController</code> 中创建了我的测试代码,一切正常。现在我将它移到了 2 个管理器类,一个用于 <code>CBCentralManager</code>,一个用于 <code>CBPeripheralManager</code> 上面的那些我制作了一个 <code>BluetoothManager</code> 的类,这是一个单例类并保存有关当前连接设备的一些信息。</p>
<p>但是,当我这样做时,我遇到了一个问题,似乎 <code>centralManager.connect()</code> 调用实际上不起作用。我调试了我的整个代码,在那一行之后似乎什么都没有发生,我似乎无法弄清楚为什么会这样或者我实际上哪里出错了。</p>
<p><strong>CentralManager 类</strong></p>
<pre><code>import Foundation
import CoreBluetooth
class CentralManager: NSObject {
private var centralManager: CBCentralManager!
var peripherals: = []
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: , options: )
default:
break
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: , 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()
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
guard let peripheralIndex = peripherals.index(of: peripheral), BluetoothManager.shared.deviceCharacteristic != 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 == nil {
BluetoothManager.shared.deviceCharacteristic = characteristic
}
}
}
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: ) {
}
}
</code></pre>
<p><strong>PeripheralManager 类</strong></p>
<pre><code>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: = [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 =
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: ) {
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)
}
}
}
</code></pre>
<p><strong>BluetoothManager 类</strong></p>
<pre><code>class BluetoothManager {
static let shared = BluetoothManager()
private var centralManager: CentralManager!
private var peripheralManager: PeripheralManager!
var deviceCharacteristic: = [:]
var connectedPeripherals: { return centralManager.peripherals }
func setup() {
centralManager = CentralManager()
peripheralManager = PeripheralManager()
}
}
</code></pre>
<p>然后在我的 <code>ViewController didLoad</code> 我正在调用 <code>BluetoothManager.shared.setup()</code></p>
<p>有谁知道为什么这些设备似乎没有相互连接,或者之后的委托(delegate)函数没有被调用?</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>当使用 <code>BluetoothManager()</code> 初始化静态 <code>shared</code> 变量时,该过程开始。我不确定在 Swift 中何时会发生这种情况,它要么是在程序的一开始,要么是在您第一次使用 <code>BluetoothManager.setup</code> 时。
变量的初始化调用<code>BluetoothManager</code> 的<code>init()</code> 方法。这将实例化一个 <code>CentralManager</code>,并调用它的 <code>init()</code> 方法。这将实例化一个 <code>CBCentralManager</code>,它将启动蓝牙进程。 </p>
<p>然后你调用<code>setup()</code>,它会实例化一个新的<code>CentralManager</code>,有它自己的<code>CBCentralManager</code>。我可以想象两个 <code>CBCentralManager</code> 出了点问题。</p>
<p>要解决它,不要使用<code>setup()</code>,而是在<code>init()</code>中初始化变量。</p>
<p>要调试这种情况,请在所有 <code>init()</code> 方法中放置断点。创建析构函数,并在其中放置断点。从技术上讲,无论如何您都需要析构函数,因为您需要从 <code>CBCentralManager</code> 对象中删除自己作为委托(delegate)。</p>
<hr/>
<p>还要注意,您只能从 <code>centralManagerDidUpdateState</code> 调用 <code>scanForPeripherals</code>。 <code>CBCentralManager</code> 在启动时可能已经处于 <code>poweredOn</code> 状态,这可能发生在另一个应用同时使用蓝牙时 - 或者当您的第一个 <code>CBCentralManager</code> 对象已经启动它。在这种情况下,将永远不会调用 <code>centralManagerDidUpdateState</code>。</p></p>
<p style="font-size: 20px;">关于ios - CoreBluetooth 功能在 Singleton 中不起作用,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/51771422/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/51771422/
</a>
</p>
页:
[1]