Search code examples
iosswiftbluetooth-lowenergycore-bluetooth

iOS BLE background reconnection


I have a problem with background reconnection with device. When I leave BLE device area, leave the iPhone for about 3 min and wait for background then go back, it won't reconnect. I tried to scan for peripheral in background but it isn't working even when I specified UUID. Is there any solution for that?

func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        dispatch_async(dispatch_get_main_queue(), {
            self.centralManager?.connectPeripheral(self.choosenPeripheral!, options: nil)  
        })    
   }

Solution

  • When the peripheral disconnects, you simply need to call connectPeripheral again in the didDisconnectPeripheral delegate method; This will create a "pending" connection and as soon as the peripheral comes back into range iOS will connect to it and call your didConnectPeripheral delegate method.

    You don't need to Dispatch the connect operation. Just use:

    func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
            central.connectPeripheral(peripheral, options: nil)    
    }