0

I am trying to get the nearest Bluetooth using CoreBluetooth framework, I import framework and implement CBCentralManagerDelegate, CBPeripheralDelegate.

Here is my code:

import CoreBluetooth

        centralManager = CBCentralManager(delegate: self, queue: nil)

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        guard central.state  == .poweredOn else {
            return
        }
        scanDevice()
    }

    func scanDevice() {

        centralManager?.scanForPeripherals(
            withServices: [transferServiceUUID], options: [
                CBCentralManagerScanOptionAllowDuplicatesKey : NSNumber(value: true as Bool)
            ]
        )
    }
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {

        print("Discovered \(peripheral.name) at \(RSSI)")
        if discoveredPeripheral != peripheral {
            discoveredPeripheral = peripheral
            print("Connecting to peripheral \(peripheral)")
            centralManager?.connect(peripheral, options: nil)
        }
    }
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("Failed to connect to \(peripheral). (\(error!.localizedDescription))")

    }
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Peripheral Connected")

        // Stop scanning
        centralManager?.stopScan()
        print("Scanning stopped")

        // Clear the data that we may already have
        data.length = 0

        // Make sure we get the discovery callbacks
        peripheral.delegate = self

        // Search only for services that match our UUID
        peripheral.discoverServices([transferServiceUUID])
    }

Why didn't I get nearest device list?

Nirmalsinh Rathod
  • 5,079
  • 4
  • 26
  • 56
  • 1
    Are you sure that your peripheral is advertising a service with the `transferServiceUUID`? – Paulw11 Jun 21 '17 at 20:15
  • Actually I am not getting neartest device. I am using Apple guideline to it. Can you help me out? – Nirmalsinh Rathod Jun 22 '17 at 02:41
  • Try first with `centralManager?.scanForPeripherals(withServices:nil, options:theSame)`. – Larme Jun 22 '17 at 10:51
  • @Larme I get some of list for device. I am not sure they are correct or not. Even I didn't able to get name of device also. – Nirmalsinh Rathod Jun 22 '17 at 11:34
  • [Github Example Libraries](https://github.com/rhummelmose/BluetoothKit) Try using these libraries and add them to your application. – Colin H Jun 21 '17 at 20:59
  • You can get a name of a peripheral from delegate method func didReadPeripheral(_ peripheral: CBPeripheral, rssi: NSNumber) {let name = peripheral.name } – Sarath Mar 16 '18 at 09:45

0 Answers0