Swift中蓝牙开发的核心是CoreBluetooth框架,它允许iOS/macOS设备与低功耗蓝牙(BLE)设备交互,以下是完整开发流程:

环境配置与权限
// Info.plist 添加隐私描述 <key>NSBluetoothAlwaysUsageDescription</key> <string>需要蓝牙权限连接设备</string> <key>NSBluetoothPeripheralUsageDescription</key> <string>与外设通信需开启蓝牙</string>
中心设备开发流程(iOS作为主机)
-
初始化中心管理器
import CoreBluetooth class BluetoothManager: NSObject, CBCentralManagerDelegate { private var centralManager: CBCentralManager! private var connectedPeripheral: CBPeripheral? override init() { super.init() centralManager = CBCentralManager(delegate: self, queue: nil) } func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == .poweredOn { central.scanForPeripherals(withServices: nil, options: nil) } } } -
发现并连接外设
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // 根据设备名称或UUID过滤 if peripheral.name?.contains("MyDevice") == true { connectedPeripheral = peripheral central.connect(peripheral, options: nil) central.stopScan() } } -
发现服务与特征值

// 遵守CBPeripheralDelegate func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let services = peripheral.services else { return } for service in services { // 根据UUID过滤目标服务 if service.uuid == CBUUID(string: "180A") { peripheral.discoverCharacteristics(nil, for: service) } } }
func peripheral(_ peripheral: CBPeripheral,
didDiscoverCharacteristicsFor service: CBService,
error: Error?) {
guard let characteristics = service.characteristics else { return }
for char in characteristics {
// 订阅通知型特征
if char.properties.contains(.notify) {
peripheral.setNotifyValue(true, for: char)
}
// 发现描述符
peripheral.discoverDescriptors(for: char)
}
4. 数据读写操作
```swift
// 写入数据到特征值
let data = Data([0x01, 0xA0])
peripheral.writeValue(data, for: char, type: .withResponse)
// 读取特征值
peripheral.readValue(for: char)
// 处理返回数据
func peripheral(_ peripheral: CBPeripheral,
didUpdateValueFor characteristic: CBCharacteristic,
error: Error?) {
guard let data = characteristic.value else { return }
// 解析数据逻辑...
}
外设模式开发(iOS作为从机)
class PeripheralManager: CBPeripheralManagerDelegate {
private var peripheralManager: CBPeripheralManager!
func setupService() {
let serviceUUID = CBUUID(string: "1230")
let charUUID = CBUUID(string: "1231")
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,
didReceiveRead request: CBATTRequest) {
// 响应读取请求
request.value = Data("Response".utf8)
peripheralManager.respond(to: request, withResult: .success)
}
}
关键问题解决方案
- 连接稳定性优化
// 重连机制 centralManager.connect(peripheral, options: [CBConnectPeripheralOptionNotifyOnDisconnectionKey: true])
// 断开回调处理
func centralManager(_ central: CBCentralManager,
didDisconnectPeripheral peripheral: CBPeripheral,
error: Error?) {
if error != nil {
central.connect(peripheral, options: nil)
}
}
2. 后台模式处理
```swift
// 在Capabilities中开启Background Modes -> Bluetooth
// 代码中声明后台任务ID
var backgroundTask: UIBackgroundTaskIdentifier?
backgroundTask = UIApplication.shared.beginBackgroundTask {
// 清理操作
UIApplication.shared.endBackgroundTask(backgroundTask!)
}
- 数据分包处理
// 大数据分包发送 let chunkSize = 20 for i in stride(from: 0, to: data.count, by: chunkSize) { let chunk = data.subdata(in: i..<min(i+chunkSize, data.count)) peripheral.writeValue(chunk, for: char, type: .withoutResponse) }
性能优化技巧

- 使用
CBCentralManagerScanOptionAllowDuplicatesKey控制扫描频率 - 连接前通过
retrieveConnectedPeripherals检查已连接设备 - 特征值操作前验证
peripheral.state == .connected
安全实践
// 配对请求处理
func peripheral(_ peripheral: CBPeripheral,
didWriteValueFor characteristic: CBCharacteristic,
error: Error?) {
if error?.localizedDescription == "Not paired" {
// 触发系统配对弹窗
peripheral.readValue(for: characteristic)
}
}
您在实际开发中遇到过哪些蓝牙连接问题?是否有特定场景(如医疗设备/IoT)需要深入探讨?欢迎在评论区分享您的经验或技术难点,我将针对性解答复杂数据传输、跨平台兼容等高级话题。
原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/32041.html