core-bluetooth
dpearson2699/swift-ios-skills
Build Bluetooth Low Energy central and peripheral workflows with Core Bluetooth scanning, connecting, and GATT communication.
What is core-bluetooth?
Core Bluetooth enables direct BLE communication for iOS apps, supporting both central role (scanning and connecting to peripherals) and peripheral role (advertising services). Use this when implementing GATT read/write/notify operations, service discovery, background BLE modes, and state restoration.
- Scan for and connect to BLE peripherals with CBCentralManager
- Discover services and characteristics on remote devices
- Read values, write data, and subscribe to notifications from BLE characteristics
- Publish local services and characteristics with CBPeripheralManager
- Handle Bluetooth authorization, background modes, and state restoration
- Manage write flow control with response/without-response modes and maximum write lengths
How to install core-bluetooth
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-bluetooth- NSBluetoothAlwaysUsageDescription key in Info.plist (required)
- UIBackgroundModes with bluetooth-central for background scanning (optional)
- UIBackgroundModes with bluetooth-peripheral for background advertising (optional)
How to use core-bluetooth
- 1.Create a CBCentralManager or CBPeripheralManager and implement the delegate protocol
- 2.Wait for the manager to reach .poweredOn state before scanning or advertising
- 3.For central role: call scanForPeripherals with service UUIDs, retain discovered peripherals, and connect
- 4.Implement CBPeripheralDelegate to discover services and characteristics on connected devices
- 5.Read values with readValue(for:), write with writeValue(_:for:type:), and subscribe with setNotifyValue(_:for:)
- 6.For peripheral role: use CBPeripheralManager to add services and publish advertisements
Use cases
- Building a heart-rate monitor app that scans for and connects to BLE fitness trackers
- Creating a smart home controller that discovers and communicates with BLE-enabled devices
- Implementing a peripheral role to advertise custom services from an iOS device
- Developing background BLE connectivity for continuous data synchronization with wearables
- Handling reconnection and state restoration when BLE devices disconnect and reconnect
- iOS app developers building BLE-enabled applications
- Wearable and IoT integration specialists
- Fitness and health app developers
- Smart home and accessory developers
core-bluetooth FAQ
Use AccessorySetupKit first for privacy-preserving accessory discovery and setup flows; then use Core Bluetooth for direct GATT communication after setup is complete.
CBCentralManager does not retain discovered peripherals. You must retain the peripheral object (e.g., in a property) or it will be deallocated and the connection will fail.
Write with response waits for confirmation from the peripheral and is slower but reliable; write without response is faster but offers no guarantee. Check characteristic properties and use peripheral.canSendWriteWithoutResponse before writing.
Core Bluetooth has no explicit permission request API. Add NSBluetoothAlwaysUsageDescription to Info.plist, create the manager when ready, check manager.authorization and manager.state, and wait for .poweredOn before scanning or advertising.
Yes, add UIBackgroundModes with bluetooth-central for background scanning or bluetooth-peripheral for background advertising in Info.plist. The system will wake your app when relevant BLE events occur.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: core-bluetooth description: "Build direct Bluetooth Low Energy workflows with Core Bluetooth. Use when implementing BLE central or peripheral GATT communication, scanning or connecting with CBCentralManager, discovering services and characteristics, reading/writing/subscribing with CBPeripheral, publishing local services with CBPeripheralManager, handling Bluetooth authorization, background BLE modes, state restoration, write flow control, or CBUUID-based workflows. For privacy-preserving accessory setup/picker flows, use accessorysetupkit first and return here for post-setup GATT communication."
Core Bluetooth
Scan for, connect to, and exchange data with Bluetooth Low Energy (BLE) devices.
Covers the central role (scanning and connecting to peripherals), the peripheral
role (advertising services), background modes, and state restoration.
Use accessorysetupkit for privacy-preserving accessory discovery and setup;
use this skill for direct Core Bluetooth GATT communication.
Contents
- Setup
- Central Role: Scanning
- Central Role: Connecting
- Discovering Services and Characteristics
- Reading, Writing, and Notifications
- Peripheral Role: Advertising
- Background BLE
- State Restoration
- Common Mistakes
- Review Checklist
- References
Setup
Info.plist Keys
| Key | Purpose |
|---|---|
NSBluetoothAlwaysUsageDescription | Required. Explains why the app uses Bluetooth |
UIBackgroundModes with bluetooth-central | Background scanning and connecting |
UIBackgroundModes with bluetooth-peripheral | Background advertising |
Bluetooth Authorization
Core Bluetooth has no explicit permission request API. Add
NSBluetoothAlwaysUsageDescription, create the manager when the app is ready for
Bluetooth access, then check manager.authorization and manager.state.
Treat .denied and .restricted as terminal until the user changes Settings;
wait for .poweredOn before scanning, connecting, advertising, or publishing
services.
Central Role: Scanning
Creating the Central Manager
Always wait for the poweredOn state before scanning.
import CoreBluetooth
final class BluetoothManager: NSObject, CBCentralManagerDelegate {
private var centralManager: CBCentralManager!
private var discoveredPeripheral: CBPeripheral?
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
guard central.state == .poweredOn else { return }
startScanning()
}
}
Scanning for Peripherals
Scan for specific service UUIDs to save power. Pass nil to discover all
peripherals (not recommended in production).
let heartRateServiceUUID = CBUUID(string: "180D")
func startScanning() {
centralManager.scanForPeripherals(
withServices: [heartRateServiceUUID],
options: [CBCentralManagerScanOptionAllowDuplicatesKey: false]
)
}
func centralManager(
_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String: Any],
rssi RSSI: NSNumber
) {
guard RSSI.intValue > -70 else { return } // Filter weak signals
// IMPORTANT: Retain the peripheral -- it will be deallocated otherwise
discoveredPeripheral = peripheral
centralManager.stopScan()
centralManager.connect(peripheral, options: nil)
}
Central Role: Connecting
func centralManager(
_ central: CBCentralManager,
didConnect peripheral: CBPeripheral
) {
peripheral.delegate = self
peripheral.discoverServices([heartRateServiceUUID])
}
func centralManager(
_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
timestamp: CFAbsoluteTime,
isReconnecting: Bool,
error: Error?
) {
if isReconnecting {
// System is automatically reconnecting
return
}
// Handle disconnection -- optionally reconnect
discoveredPeripheral = nil
}
Discovering Services and Characteristics
Implement CBPeripheralDelegate to walk the service/characteristic tree.
extension BluetoothManager: CBPeripheralDelegate {
func peripheral(
_ peripheral: CBPeripheral,
didDiscoverServices error: Error?
) {
guard let services = peripheral.services else { return }
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(
_ peripheral: CBPeripheral,
didDiscoverCharacteristicsFor service: CBService,
error: Error?
) {
guard let characteristics = service.characteristics else { return }
for characteristic in characteristics {
if characteristic.properties.contains(.notify) {
peripheral.setNotifyValue(true, for: characteristic)
}
if characteristic.properties.contains(.read) {
peripheral.readValue(for: characteristic)
}
}
}
}
Reading, Writing, and Notifications
Reading a Value
func peripheral(
_ peripheral: CBPeripheral,
didUpdateValueFor characteristic: CBCharacteristic,
error: Error?
) {
guard let data = characteristic.value else { return }
switch characteristic.uuid {
case CBUUID(string: "2A37"):
if let heartRate = parseHeartRate(data) {
print("Heart rate: \(heartRate) bpm")
}
case CBUUID(string: "2A19"):
let batteryLevel = data.first.map { Int($0) } ?? 0
print("Battery: \(batteryLevel)%")
default:
break
}
}
private func parseHeartRate(_ data: Data) -> Int? {
guard data.count >= 2 else { return nil }
let flags = data[0]
let is16Bit = (flags & 0x01) != 0
if is16Bit {
guard data.count >= 3 else { return nil }
return Int(data[1]) | (Int(data[2]) << 8)
} else {
return Int(data[1])
}
}
Writing a Value
func writeValue(_ data: Data, to characteristic: CBCharacteristic,
on peripheral: CBPeripheral,
preferResponse: Bool = true) {
let type: CBCharacteristicWriteType
if preferResponse, characteristic.properties.contains(.write) {
type = .withResponse
} else if characteristic.properties.contains(.writeWithoutResponse),
peripheral.canSendWriteWithoutResponse {
type = .withoutResponse
} else if characteristic.properties.contains(.write) {
type = .withResponse
} else {
return
}
guard data.count <= peripheral.maximumWriteValueLength(for: type) else { return }
peripheral.writeValue(data, for: characteristic, type: type)
}
// Confirmation callback for .withResponse writes.
func peripheral(
_ peripheral: CBPeripheral,
didWriteValueFor characteristic: CBCharacteristic,
error: Error?
) {
if let error {
print("Write failed: \(error.localizedDescription)")
}
}
// Resume queued .withoutResponse writes here.
func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) {}
Subscribing to Notifications
// Subscribe
peripheral.setNotifyValue(true, for: characteristic)
// Unsubscribe
peripheral.setNotifyValue(false, for: characteristic)
// Confirmation
func peripheral(
_ peripheral: CBPeripheral,
didUpdateNotificationStateFor characteristic: CBCharacteristic,
error: Error?
) {
if characteristic.isNotifying {
print("Now receiving notifications for \(characteristic.uuid)")
}
}
Peripheral Role: Advertising
Publish services from the local device using CBPeripheralManager.
final class BLEPeripheralManager: NSObject, CBPeripheralManagerDelegate {
private var peripheralManager: CBPeripheralManager!
private let serviceUUID = CBUUID(string: "12345678-1234-1234-1234-123456789ABC")
private let charUUID = CBUUID(string: "12345678-1234-1234-1234-123456789ABD")
override init() {
super.init()
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
guard peripheral.state == .poweredOn else { return }
setupService()
}
private func setupService() {
let characteristic = CBMutableCharacteristic(
type: charUUID,
properties: [.read, .notify],
value: nil,
permissions: [.readable]
)
let service = CBMutableService(type: serviceUUID, primary: true)
service.characteristics = [characteristic]
peripheralManager.add(service)
}
func peripheralManager(
_ peripheral: CBPeripheralManager,
didAdd service: CBService,
error: Error?
) {
guard error == nil else { return }
peripheralManager.startAdvertising([
CBAdvertisementDataServiceUUIDsKey: [serviceUUID],
CBAdvertisementDataLocalNameKey: "MyDevice"
])
}
}
Background BLE
Background Central Mode
Add bluetooth-central to UIBackgroundModes. In the background:
- Scanning must specify one or more service UUIDs;
nilscans are foreground-only - Scan options, including
CBCentralManagerScanOptionAllowDuplicatesKey, have no effect
Background Peripheral Mode
Add bluetooth-peripheral to UIBackgroundModes. In the background:
- Without this mode, published service contents are disabled while suspended
- The local name is not advertised
- Service UUIDs move to the overflow area and require explicit service scans
State Restoration
State restoration allows the system to re-create your central or peripheral manager after your app is terminated and relaunched for a BLE event.
Central Manager State Restoration
// 1. Create with a restoration identifier
centralManager = CBCentralManager(
delegate: self,
queue: nil,
options: [CBCentralManagerOptionRestoreIdentifierKey: "myCentral"]
)
// 2. Implement the restoration delegate method
func centralManager(
_ central: CBCentralManager,
willRestoreState dict: [String: Any]
) {
if let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey]
as? [CBPeripheral] {
for peripheral in peripherals {
// Re-assign delegate and retain
peripheral.delegate = self
discoveredPeripheral = peripheral
}
}
let restoredServices = dict[CBCentralManagerRestoredStateScanServicesKey]
as? [CBUUID]
let restoredOptions = dict[CBCentralManagerRestoredStateScanOptionsKey]
as? [String: Any]
// Resume scanning with restoredServices/restoredOptions if still needed.
}
Peripheral Manager State Restoration
peripheralManager = CBPeripheralManager(
delegate: self,
queue: nil,
options: [CBPeripheralManagerOptionRestoreIdentifierKey: "myPeripheral"]
)
func peripheralManager(
_ peripheral: CBPeripheralManager,
willRestoreState dict: [String: Any]
) {
let services = dict[CBPeripheralManagerRestoredStateServicesKey]
as? [CBMutableService]
let advertisement = dict[CBPeripheralManagerRestoredStateAdvertisementDataKey]
as? [String: Any]
// Reconnect app state to restored services/advertisement as needed.
}
Common Mistakes
| Mistake | Fix |
|---|---|
Scan/connect before .poweredOn | Start BLE work from centralManagerDidUpdateState. |
| Discovered peripheral is not retained | Hold a strong reference through connection and discovery. |
Production scan passes nil services | Filter by the service UUIDs the feature needs. |
Service discovery begins before didConnect | Advance only from delegate callbacks and handle failure/disconnect paths. |
| Writes ignore characteristic properties or payload limits | Select the supported write type, respect maximumWriteValueLength, and gate .withoutResponse on canSendWriteWithoutResponse. |
Review Checklist
-
NSBluetoothAlwaysUsageDescriptionadded to Info.plist - All BLE operations gated on
centralManagerDidUpdateStatereturning.poweredOn - Discovered peripherals retained with a strong reference
- Scanning uses specific service UUIDs (not
nil) in production -
CBPeripheralDelegateset before callingdiscoverServices - Characteristic properties checked before read/write/notify
- Write payloads stay within
maximumWriteValueLength(for:) -
.withoutResponsewrites honorcanSendWriteWithoutResponse - Background mode (
bluetooth-centralorbluetooth-peripheral) added if needed - State restoration identifier set if app needs relaunch-on-BLE-event support
-
willRestoreStatedelegate method implemented when using state restoration - Scanning stopped after discovering the target peripheral
- Disconnection handled with optional automatic reconnect logic
- Write type matches characteristic properties (
.withResponsevs.withoutResponse)
References
- Extended patterns (reconnection strategies, data parsing, SwiftUI integration): references/ble-patterns.md
- Core Bluetooth framework
- CBCentralManager
- CBPeripheral
- CBPeripheralManager
- CBService
- CBCharacteristic
- CBUUID
- CBCentralManagerDelegate
- CBPeripheralDelegate
- NSBluetoothAlwaysUsageDescription
- CBManagerAuthorization
- scanForPeripherals(withServices:options:)
- startAdvertising(_:)
- writeValue(_:for:type:)
- maximumWriteValueLength(for:)
- canSendWriteWithoutResponse
- Configuring background execution modes
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

core-data
Build and maintain Core Data persistence for apps not using SwiftData, with concurrency, batch operations, and schema migration.

core-motion
Access iOS device motion sensors: accelerometer, gyroscope, magnetometer, pedometer, activity recognition, altitude, and more.

core-nfc
Read and write NFC tags on iPhone using CoreNFC framework.

coreml
Load, configure, and run Core ML models in iOS apps for on-device machine learning inference.

cryptokit
Apple CryptoKit for Swift cryptographic primitives: hashing, HMAC, AES-GCM, signing, key agreement, and post-quantum operations.

cryptotokenkit
Access security tokens and smart cards via CryptoTokenKit for token drivers, NFC sessions, and certificate-based authentication.