Search code examples
iosswiftsingletoncore-bluetooth

Observers in view controllers from Bluetooth singleton class in Swift


I have created a singleton class to interact with multiple view controllers. How do I notify about the Bluetooth state from a singleton class?

import UIKit
import CoreBluetooth
        
class MyBluetoothManager: CBCentralManagerDelegate, CBPeripheralDelegate{
       
        static let shared = MyBluetoothManager()
        
        let central = CBCentralManager(delegate: MyCentralManagerDelegate.shared,
                                       queue: nil, options: nil)
}  

I will be implementing delegates of CBPeripheral in the future. Suggest me if there any existing blog or not.


Solution

  • You can consider NotificationCenter.

    In your view controllers you need to add observer for your custom type of notification. E.g.:

    NotificationCenter.default.addObserver( self, selector: #selector( self.methodtohandle ), name: .yourcustomeventname, object: nil )
    

    don't forget to remove the observer when the controller is no longer needed/presented:

    NotificationCenter.default.removeObserver(self, name: .yourcustomeventname, object: nil)
    

    and on your singleton class you would call "post":

    NotificationCenter.default.post(name: .yourcustomeventname, object: somedata)