Caroline
Caroline

Reputation: 31

finding nearby bluetooth devices with swift

I am currently using swift to make an app that can generate a list of bluetooth devices nearby. However, I cannot find any documents that use swift to do that. All of the files are in Objective C and I am wondering if I can just make an objective C file and connect directly to the storyboard? (my project file is in swift).

Also, do I have to include any other library from outside? (ex: serialGATT) or coreBluetooth.framework is good enough?

Upvotes: 3

Views: 5568

Answers (1)

jaredwolff
jaredwolff

Reputation: 807

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.

Upvotes: 1

Related Questions