1

I am new to Corebluetooth. I want to prevent duplicate peripherals when scanning. Can anyone help me?
And one more question, how to connect peripheral with in range ?

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) 
 {
    if (peripheral.name != nil) && (peripheral.name == "EXP") || 
  (peripheral.name == "EXP") 
      {


        let key = peripheral.identifier.uuidString
        let data = advertisementData.description

        if let previous = datas[key]
        {
            if (previous != data)
            {
                print("Different \(String(describing: peripheral.name)): \ . (data)")
            }
        } else
        {
            print("\(String(describing: peripheral.name)): \(data)");
            datas[key] = data
        }

            peripherals.append(peripheral)
        lblDeviceCount.isHidden = false
        lblDeviceCount.text = "\(peripherals.count) Devices Found"

            tblPeriPheral.reloadData()
     }

}
Larme
  • 22,070
  • 5
  • 50
  • 76

1 Answers1

2

You can use a loop to prevent duplicate peripherals. If new peripheral has an identifier equal to an existing peripheral in peripherals (the variable you are using) then don't append it to peripherals.

for existing in peripherals {
    if existing.identifier == peripheral.identifier { return }
}

For the second part, you should read about RSSI, it will help you know whether you're closer or far from the device. Depending on the range you can make decision whether to connect to it or not.

Hadi
  • 109
  • 9
  • This unfortunately doesn't prevent duplicates, as `identifier` is not a stable ID. Apple is inventing a new identifier for the same peripheral every now and then, for privacy reasons. – pipacs Jun 30 '20 at 09:17