提到藍牙,很多人會想到穿戴設備,但從本質上看,它又是一種近距離通信協議。CoreBluetooth 是蘋果提供的藍牙框架,理解它的關鍵在於 Peripheral、Central、Service 與 Characteristic 這幾個概念。

在 CoreBluetooth 中,Peripheral 通常扮演服務端角色,它廣播自己支持的 Service;Central 則像客戶端,掃描並連接感興趣的 Peripheral。每個 Service 下可以包含多個 Characteristic,Characteristic 才是真正承載數據讀寫與通知的單位。
可以把 Peripheral 看作提供服務的設備,把 Central 看作使用服務的設備。Central 連接 Peripheral 後,發現 Service,再發現 Characteristic,最後通過 Characteristic 建立雙向數據通道。
作為服務端,需要先創建 CBPeripheralManager,然後添加 Service 與 Characteristic,最後開始廣播。
self.peripheral = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
CBMutableService *service = [[CBMutableService alloc]
initWithType:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]
primary:YES];
self.characteristic = [[CBMutableCharacteristic alloc]
initWithType:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]
properties:CBCharacteristicPropertyNotify | CBCharacteristicPropertyWrite
value:nil
permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
service.characteristics = @[self.characteristic];
[self.peripheral addService:service];
[self.peripheral startAdvertising:@{
CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]
}];Central 端需要先掃描指定 Service 的 Peripheral,連接成功後發現 Service 與 Characteristic,然後訂閱通知。
self.central = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
[self.central scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]
options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}];
[self.central connectPeripheral:peripheral options:nil];
[peripheral discoverServices:@[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]]];
[peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]
forService:service];
[peripheral setNotifyValue:YES forCharacteristic:characteristic];訂閱完成後,Peripheral 可以通過 updateValue:forCharacteristic:onSubscribedCentrals: 向 Central 發送數據,Central 則在 didUpdateValueForCharacteristic:error: 中接收。
Central 也可以通過 writeValue:forCharacteristic:type: 向 Peripheral 寫入數據,Peripheral 會在 peripheralManager:didReceiveWriteRequests: 中收到請求。由於藍牙傳輸的是二進制流,業務層通常需要自定義協議,將數據拆包、組包並校驗。
在多個 Central 同時連接同一個 Peripheral 時,需要注意請求來源判斷。某些系統版本或測試環境下,CBATTRequest 的 Central 指向前一個連接對象,可能導致業務層無法正確區分數據來源。遇到此類問題時,應在協議層加入設備標識或會話標識。
藍牙不僅可用於穿戴設備,也可以用於近距離聊天、局域網同步、小型遊戲對戰等場景。由於其無需依賴外部服務器,鏈路相對封閉,適合對延遲與隱私有要求的近場通信。
CoreBluetooth 的學習重點在於理解 CS 架構與數據通道的建立過程。只要理清 Peripheral、Central、Service、Characteristic 的關係,再配合自定義協議,就能完成大多數藍牙業務開發。