You'll have to import CoreBluetooth
import CoreBluetooth
Add the CBCentralManagerDelegate
to your controller. (For a simple app I attached it to my View Controller)
class ViewController: UIViewController, CBPeripheralDelegate, CBCentralManagerDelegate {
You should create a local variable centralManager
(or similar) and then initialize in your viewDidLoad
function
centralManager = CBCentralManager(delegate: self, queue: nil)
Finally you can create a new function called centralManagerDidUpdateState
which will act as a callback when the Bluetooth state changes (it's always called on startup in your app.
// If we're powered on, start scanning
func centralManagerDidUpdateState(_ central: CBCentralManager) {
print("Central state update")
if central.state != .poweredOn {
print("Central is not powered on")
} else {
print("Central scanning for", ParticlePeripheral.particleLEDServiceUUID);
centralManager.scanForPeripherals(withServices: [ParticlePeripheral.particleLEDServiceUUID],
options: [CBCentralManagerScanOptionAllowDuplicatesKey : true])
}
}
The important call is centralManager.scanForPeripherals
This will start the scanning process. In my case I'm filtering devices that only have ParticlePeripheral.particleLEDServiceUUID
in their advertising packets.
That should get you scanning and on your way. I wrote a full end-to-end tutorial on how to use Swift with Bluetooth. It will go into much more detail. Here it is.