1
votes

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)  
        })    
   }
1
You need to show some code, but essentially when you get a call to the didDisconnect delegate method you should immediately call connect on the peripheral. Then, when it comes back into range you will reconnect to it. - Paulw11
I call connect in didDisconnect: gist.github.com/anonymous/d84ec2b18f9937d86d6ca44e6e3aa708 I set choosen peripheral after first connection, I also tried put connection in dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) - Daloteon
Please edit your question to show relevant code. - Paulw11
You don't need the Dispatch. All you need is centralManager.connectPeripheral(peripheral, options: nil). Make sure you have the appropriate Bluetooth background mode enabled on your app capabilities. You also need to opt in to Bluetooth state restoration for long-term background operations so that iOS can relaunch your app if required. Do not use a UIViewController to hold your CBCentralManager and related properties. Use another class that is held by your AppDelegate or implemented as a Singleton. - Paulw11
I store it in singleton. I will try without dispatch and reply after tests. Thanks for your help! - Daloteon

1 Answers

3
votes

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