I am trying to code out a background refresh part of my app but there are two centralManager functions in the app.
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if peripheral.identifier.uuidString == selected {
selectedPeripheral = peripheral
centralManager?.stopScan()
centralManager?.connect(selectedPeripheral!, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Connected to peripheral: \(peripheral)")
// Subscribe to disconnection events
peripheral
.publisher(for: \.state)
.sink { [weak self] state in
if state == .connected {
self?.isConnected = true
} else if state == .disconnected {
// Peripheral is disconnected, send notification
if self?.isConnected == true {
self?.sendNotification()
self?.isConnected = false
}
}
}
.store(in: &cancellables)
}
and this is the refresh part
private func handleBluetoothMonitoring(task: BGAppRefreshTask, bluetoothMonitor: BluetoothMonitor) {
let queue = DispatchQueue(label: "com.yourcompany.bluetoothmonitor")
task.expirationHandler = {
// Handle expiration of the task if needed
}
queue.async {
// Perform Bluetooth monitoring tasks here
if let centralManagerInstance = bluetoothMonitor.centralManager {
DispatchQueue.main.async {
bluetoothMonitor.centralManagerDidUpdateState(centralManagerInstance)
}
} else {
print("Central manager is nil")
}
// End the task
task.setTaskCompleted(success: true)
}
}
Is there a way to solve this? Thanks!