简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM