(一)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:
这个方法会告诉我们,写操作成功与否
外设模式请查看:
http://blog.csdn.net/flover5724059/article/details/73521754
还没有评论,来说两句吧...