CoreBluetooth abstraction layer for iOS and macOS development environments.
- Swift Concurrency compatible
- SwiftUI compatible
- Apple's APIs dependencies only
It is currently supported on:
iOS 13.0+ macOS 10.15+
As simple as creating a CBCentralManager and let the reactive magic of Combine do the rest:
import CoreBluetooth
import Combine
import BLECombineKit
...
let centralManager = BLECombineKit.buildCentralManager(with: CBCentralManager())
let serviceUUID = CBUUID(string: "0x00FF")
let characteristicUUID = CBUUID(string: "0xFF01")
// Connect to the first peripheral that matches the given service UUID and observe a specific
// characteristic in that service.
centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
.first()
.flatMap { $0.peripheral.connect(with: nil) }
.flatMap { $0.discoverServices(serviceUUIDs: [serviceUUID]) }
.flatMap { $0.discoverCharacteristics(characteristicUUIDs: nil) }
.filter { $0.value.uuid == characteristicUUID }
.flatMap { $0.observeValueUpdateAndSetNotification() }
.sink(receiveCompletion: { completion in
print(completion)
}, receiveValue: { data in
print(data.value)
})
.store(in: &disposables)
And with Swift Concurrency, it would look like this:
import CoreBluetooth
import Combine
import BLECombineKit
...
let centralManager = BLECombineKit.buildCentralManager(with: CBCentralManager())
let serviceUUID = CBUUID(string: "0x00FF")
let characteristicUUID = CBUUID(string: "0xFF01")
// Connect to the first peripheral that matches the given service UUID and observe a specific
// characteristic in that service.
let stream = centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
.first()
.flatMap { $0.peripheral.connect(with: nil) }
.flatMap { $0.discoverServices(serviceUUIDs: [serviceUUID]) }
.flatMap { $0.discoverCharacteristics(characteristicUUIDs: nil) }
.filter { $0.value.uuid == characteristicUUID }
.flatMap { $0.observeValueUpdateAndSetNotification() }
.values
Task {
for try await value in stream {
print("Value received \(value)")
}
}
In Xcode, select File --> Swift Packages --> Add Package Dependency and then add the following url:
https://github.com/Henryforce/BLECombineKit