Scanning for Peripherals
Once the CBCentralManager is up and powered on, you can create a function that scan for peripherals around us.
Create a function called startScanning
. Call the method scanForPeripherals(withServices:)
.
This method scans for peripherals that are advertising services. Now since the unique identifier is set up, add that reference to the method.
func startScanning() -> Void { // Start Scanning centralManager?.scanForPeripherals(withServices: [CBUUIDs.BLEService_UUID]) }
Now add the startScanning()
function to the centralManagerDidUpdateState
to scan as soon as the app opens.
extension ViewController: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case .poweredOff: print("Is Powered Off.") case .poweredOn: print("Is Powered On.") startScanning() case .unsupported: print("Is Unsupported.") case .unauthorized: print("Is Unauthorized.") case .unknown: print("Unknown") case .resetting: print("Resetting") @unknown default: print("Error") } } }
When you run your app, your device will start scanning for peripherals.
Discovering Peripherals
Now that scanning is started, what happens when a peripheral is discovered?
Every time a peripheral is discovered, the CBCentralManager will notify you by calling the centralManager(_:didDiscover:advertisementData:rssi:)
function on its delegate.
This function provides the following information about the newly discovered peripheral:
- The discovered peripheral is recognized and can be stored as a CBPeripheral.
- The discovered peripheral has stored advertisement data.
- The current received signal strength indicator (RSSI) of the peripheral, in decibels.
Since you are interested in connecting to one peripheral, create an instance of a peripheral.
private var bluefruitPeripheral: CBPeripheral!
Call the didDiscover function. This tells the delegate the central manager discovered a peripheral while scanning for devices.
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,advertisementData: [String : Any], rssi RSSI: NSNumber) { bluefruitPeripheral = peripheral bluefruitPeripheral.delegate = self print("Peripheral Discovered: \(peripheral)") print("Peripheral name: \(peripheral.name)") print ("Advertisement Data : \(advertisementData)") centralManager?.stopScan() }
The implementation of this function performs the following actions:
- Set the
bluefruitPeripheral
variable to the new peripheral found. - Set the peripheral's delegate to self (ViewController)
- Printed the newly discovered peripheral's information in the console.
- Stopped scanning for peripherals.
Next up - actually connect to that peripheral.