Skip to content

Disconnect Connection When device lost connection #405

@andrewehab

Description

@andrewehab

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()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions