theDC
theDC

Reputation: 6484

Swift 3: How to scan for peripherals in background?

Here is my scenario:

I connect with two peripherals, put my app in the background mode and begin getting away with peripherals until they lost connection to my app. When coming back, they are not connecting again when in reach.

When I perform the same experiment when app is running in the foreground, no issues occurred - coming with peripherals closer to iPhone results in reconnecting.

However, I see in the console that when peripherals are losing connection, the DidDisconnectPeripheral method is being called. The problem is that scanning is not called inside this method

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    numberOfTagsSending = numberOfTagsSending - 1
    numberOfConnectedTags = numberOfConnectedTags - 1
    print("Tag was disconnected. Start scanning.")

    synchronizer.alreadySynced = false

    central.scanForPeripherals(withServices: arrayOfServices, options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
}

I read this answer and did everything exactly the same way, unfortunately it does not work.

Thanks in advance

Upvotes: 2

Views: 3498

Answers (1)

Paulw11
Paulw11

Reputation: 114783

Once you have a CBPeripheral instance you don't need to discover it again. You can simply connect to it; if the peripheral isn't currently in range then iOS will automatically connect once the peripheral comes into range and will call your didConnectPeripheral delegate method.

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    numberOfTagsSending = numberOfTagsSending - 1
    numberOfConnectedTags = numberOfConnectedTags - 1

    central.connect(peripheral)
}

Upvotes: 4

Related Questions