Polidea / RxBluetoothKit

iOS & OSX Bluetooth library for RxSwift
Apache License 2.0
1.41k stars 365 forks source link

Disconnect Connection When device lost connection #405

Open andrewehab opened 2 years ago

andrewehab commented 2 years ago

When terminated the app the connection is still restored but when the device lose connection it can't reconnect again

class BluetoothManager { //MARK: - Singelton static let shared = BluetoothManager()
//MARK: - Propertise var centralManager: CentralManager!

//MARK: - Configure Central Manager
func configureCentralManager() {
    //        let options = [CBCentralManagerOptionRestoreIdentifierKey: "NOUR", CBCentralManagerOptionShowPowerAlertKey: true] as [String: AnyObject]

    centralManager = CentralManager(
        options: [CBCentralManagerOptionRestoreIdentifierKey: NSString("NOUR")],
        onWillRestoreCentralManagerState: { (restoreState) in
            print("RESTORED")
            print(restoreState.centralManager )
        })
}

//MARK: - Start Scanning For Peripherals
func startScanningForPeripherals() {
    _ = centralManager.observeState()
        .startWith( centralManager.state )
        .filter { $0 == .poweredOn }
        .flatMap { _ in self.centralManager.scanForPeripherals(withServices: [self.beaconServiceCBUUID]) }
        .subscribe(onNext: { [weak self] scannedPeripheral in
            guard let self = self else { return }
            self.configureScannedPeripherals(scannedPeripheral: scannedPeripheral)
        }, onError: { [weak self] error in
            guard let self = self else { return }
           print("\(error)")

        })
}

//MARK: - Connect To Peripheral Devices
func connectToPeripheralDevices(peripheral: Peripheral) {
    peripheral.establishConnection()
        .flatMap { $0.discoverServices(nil) }.asObservable()
        .flatMap { Observable.from($0) }
        .flatMap { $0.discoverCharacteristics(nil)}.asObservable()
        .flatMap { Observable.from($0) }
        .filter({ $0.properties.contains(.read) })
        .flatMap { $0.readValue() }
        .subscribe(onNext: {
            let data = $0.value
        }, onError: { error in
            print(error)
        }).disposed(by: disposeBag)
 }

}

// In App Delegate func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { BluetoothManager.shared.configureCentralManager() }