1. 程式人生 > >(一)CoreBluetooth iOS 藍芽 “中心模式”

(一)CoreBluetooth iOS 藍芽 “中心模式”

使用Corebluetooth框架進行藍芽開發,有兩種模式:一種是中心模式,另一種是外設模式。
中心模式
分為以下幾步:
1.建立中心裝置 2.掃描外部裝置 3.連線外部裝置 4.掃描外部裝置的服務和特徵 5.利用外部裝置的特徵與外部裝置手法資料

一、首先匯入框架 CoreBluetooth/CoreBluetooth.h
建立中心裝置並設定代理
CBCentralManager *manager = [CBCentralManager alloc]init];
一旦設定代理,在程式執行的時候就會呼叫協議方法
- (void)centralManagerDidUpdateState:(CBCentralManager*)central ;
- 這個方法是判斷中心裝置是否開啟藍芽裝置

二、利用中心裝置掃描外部裝置
[manager scanForPeripheralsWithServices: option:];
第一個引數表示掃描帶有相關服務的外部裝置,例如填寫@[[CBUUID UUIDWithString:@”需要連線的外部裝置的服務的UUID”]] nil 表示掃描全部裝置
options @{CBCentralManagerScanOptionAllowDuplicatesKey : YES}
一旦掃描到有外部裝置
- centalManager:(CBCentraManager*)centralManager didDiscoverPeripheral:() advertisementData:(NSDictionary*)
- 在這個協議裡,我們可以根據我們獲取到的硬體的某些條件進行篩選,然後連線我們需要連線的外部裝置,例如連線名字帶有”*

“的外部裝置
- if(peripheral.namehasPrefix:@”*“){
連線裝置
manager connectPeripheral:peripheral options:nil];
}
-(void)peripheral: didDiscoverCharacteristicsForService: error: ;

5、掃描到特徵之後,我們就可以拿到特徵進行讀寫操作
例如進行讀取資料的操作:
if([characteristic.UUID.UUIDStringisEqualToString:@”“]){
peripheral readValueForCharacteristic:characteristic];
}
只要讀取了就會進入另一個協議方法

-(void)peripheral: didUpdateValueForCharacteristic:
在這個方法裡我們就拿到了我們需要的資料,進行寫的操作是:
peripheral writeValue: forCharacteristic: type:

每寫一次資料就會進入

-(void)peripheral: didWriteValueForCharacteristc: error: