您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 藍牙開發入門:CoreBluetooth 中心模式使用小結

編輯:iOS 開發綜合

本文總結了在 iOS 上使用 CoreBluetooth 建立藍牙通訊的要点。由於實際專案主要涉及中心(Central)模式,因此以下僅針對中心模式進行說明。建議搭配官方文件一併閱讀。

前期準備

1、引入 CoreBluetooth.framework。

2、實作藍牙協議,例如:

// .h 檔
#import 
@interface ViewController : UIViewController 
@end
// .m 檔中補上對應的代理方法即可

讓藍牙動起來的流程

3.1 建立 CBCentralManager 實例並設定代理,同時建立陣列管理外設:

self.cbCentralMgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
self.cbCentralMgr.delegate = self;
self.peripheralArray = [NSMutableArray array];

3.2 掃描周圍的藍牙。可發現的藍牙會持續發送廣告訊息,中心設備便是透過接收這些訊息來發現它們:

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], CBCentralManagerScanOptionAllowDuplicatesKey, nil];
[self.cbCentralMgr scanForPeripheralsWithServices:nil options:dic];

3.3 發現藍牙設備時,CBCentralManager 會通知代理處理:

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
    // 若周圍有多個藍牙,此方法會被呼叫多次
}

3.4 連接藍牙,一個中心設備可同時連接多個外設:

[self.cbCentralMgr connectPeripheral:peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    peripheral.delegate = self; // 為外設設置代理
}

3.5 查詢藍牙服務:

[peripheral discoverServices:nil];
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    for (CBService* service in peripheral.services) {
        // 處理每個服務
    }
}

3.6 查詢服務所帶的特徵值:

[peripheral discoverCharacteristics:nil forService:service];
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    for (CBCharacteristic *characteristic in service.characteristics) {
        // 處理每個特徵值
    }
}

3.7 給藍牙發送資料:

[peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
}

3.8 處理藍牙發送過來的資料:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    // 從 characteristic.value 中讀取資料
}

3.9 透過 identifier 檢索已發現的外設:

NSMutableArray *Identifiers = [NSMutableArray array];
for (CBPeripheral *peripheral in self.peripheralArray) {
    [Identifiers addObject:peripheral.identifier];
}
self.retrievePeripherals = [self.cbCentralMgr retrievePeripheralsWithIdentifiers:Identifiers];

3.10 透過服務檢索已連接的外設:

self.retrievePeripherals = [self.cbCentralMgr retrieveConnectedPeripheralsWithServices:services];

以上就是藍牙中心模式的大致流程。範例中的參數設定及其他代理方法,建議自行深入研究,因為作者本身也才剛入門,歡迎交流指正。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved