Last active
January 24, 2021 19:27
-
-
Save Kdan/9eada1a9e73f497c4b3d2583eaf3cca1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreBluetooth | |
class BluetoothManager: NSObject { | |
private let centralManager = CBCentralManager() | |
private let uuids: [CBUUID] = [.init(string: "EXAMPLE-UUID-1"), | |
.init(string: "EXAMPLE-UUID-2")] | |
override init() { | |
super.init() | |
centralManager.delegate = self | |
} | |
} | |
extension BluetoothManager: CBCentralManagerDelegate { | |
func centralManagerDidUpdateState(_ central: CBCentralManager) { | |
// Make sure the central manager is powered on. | |
guard central.state == .poweredOn else { return } | |
// We only scan for the listed UUIDs. | |
central.scanForPeripherals(withServices: uuids, options: nil) | |
} | |
func centralManager(_ central: CBCentralManager, | |
didDiscover peripheral: CBPeripheral, | |
advertisementData: [String : Any], | |
rssi RSSI: NSNumber) { | |
// Only connect to peripherals with names and manufacturer data. | |
guard let name = peripheral.name ?? advertisementData[CBAdvertisementDataLocalNameKey] as? String, | |
let data = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data, | |
name != "FORBIDDEN-NAME", | |
!data.isEmpty else { return } | |
central.connect(peripheral, options: nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment