Configure Beacons with CoreBluetooth
suggest changeIntroduction
How to read and write data on a Bluetooth Low Energy device.
Remarks
Some important points
- Central-mode scanning does not use a background capability. On iOS 13 and later, add
NSBluetoothAlwaysUsageDescription(Privacy - Bluetooth Always Usage Description). Background BLE still needs the Bluetooth background mode. - Apple devices store bytes in little-endian order. Check whether the accessory does too. Intel CPUs are usually little-endian, and the ARM chips in iPhones are little-endian as well.
- After a single operation or a batch, the connection is dropped, so reconnect before you continue.
Scan for SERVICE UUID
func SearchBLE(){
cb_manager.scanForPeripherals(withServices:[service_uuid], options: nil)
StopSearchBLE()
}
How to discover SERVICE UUID without documentation
func centralManager(_ central: CBCentralManager, didConnect peripheral:
CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
print("Service: \(service)\n error: \(error)")
}
}
-
discoverServices(nil)returns every service. That is slower and includes services you may not need. -
If you don’t already know the service UUID, run this code and look in the console.
-
This example found 3 services: Battery, Device Information (firmware), and FFF0.
-
FFF0 is the service UUID in this example. It is not a standard service. Assigned service UUIDs are listed here.
Convert data to UInt16 and back
Add these extensions to your project. init?(data:) loads the bytes in host order. The UInt16.data getter writes them big-endian, which matches a typical major value.
protocol DataConvertible {
init?(data: Data)
var data: Data { get }
}
extension DataConvertible {
init?(data: Data) {
guard data.count == MemoryLayout<Self>.size else { return nil }
self = data.withUnsafeBytes { $0.pointee }
}
var data: Data {
var value = self
return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
}
extension UInt16 : DataConvertible {
init?(data: Data) {
guard data.count == MemoryLayout<UInt16>.size else { return nil }
self = data.withUnsafeBytes { $0.pointee }
}
var data: Data {
var value = CFSwapInt16HostToBig(self)
return Data(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents