首先導(dǎo)入庫#import<CoreBluetooth/CoreBluetooth.h>
遵循代理:<CBCentralManagerDelegate,CBPeripheralDelegate>
聲明變量:
@property(nonatomic,strong)CBCentralManager*bluetoothManager;
@property(nonatomic,strong)CBPeripheralManager*manager;
1、創(chuàng)建中心設(shè)備并設(shè)置代理:
self.bluetoothManager=[[CBCentralManageralloc]initWithDelegate:self queue:dispatch_get_main_queue()];
self.manager=[[CBPeripheralManageralloc]initWithDelegate:self queue:nil];
CBCentralManagerDelegate代理必須執(zhí)行方法是查看中心設(shè)備狀態(tài)是否打開藍(lán)牙:
-(void)centralManagerDidUpdateState:(CBCentralManager
*)central{
switch (central.state) {
case CBCentralManagerStateUnknown:
break;
case CBCentralManagerStateResetting:
break;
case CBCentralManagerStateUnsupported:
break;
case CBCentralManagerStateUnauthorized:
break;
case CBCentralManagerStatePoweredOff:
break;
case CBCentralManagerStatePoweredOn:
break;
default:
break;
}
}
2、開始掃描外部設(shè)備:
[self.bluetoothManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO }];
第一個參數(shù)那里表示掃描帶有相關(guān)服務(wù)的外部設(shè)備晌块,例如填寫
@[[CBUUID UUIDWithString:@"需要連接的外部設(shè)備的服務(wù)的UUID"]],即表示帶有需要連接的外部設(shè)備的服務(wù)的UUID的外部設(shè)備否灾,nil表示掃描全部設(shè)備;
@{ CBCentralManagerScanOptionAllowDuplicatesKey : @NO }
NO表示不會讓中心設(shè)備不斷地監(jiān)聽外部設(shè)備的消息鸣奔,YES就是能不斷地監(jiān)聽外部設(shè)備消息墨技。
3、一旦掃描到外部設(shè)備挎狸,就會進(jìn)入?yún)f(xié)議中:
-(void)centralManager:(CBCentralManager *)centraldidDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
//找到的設(shè)備必須持有它扣汪,否則CBCentralManager中也不會保存peripheral,那么CBPeripheralDelegate中的方法也不會被調(diào)用锨匆!
在這里可以根據(jù)我們所知道的硬件設(shè)備條件來篩選所需要的設(shè)備崭别,將其他打開藍(lán)牙的設(shè)備排除在外。
例如:搜找硬件盒子名字為JL的設(shè)備:
@property (nonatomic, strong) NSMutableArray *peripherals;
@property(nonatomic, strong) NSMutableArray *peripheralsNameArray;
初始化數(shù)組略
if (! [self.peripherals containsObject:peripheral]) {
[self.peripherals addObject:peripheral];
}
NSArray *tempPeripherals = [self.peripheralscopy];
for (CBPeripheral *per intempPeripherals) {
if (! [self.peripheralsNameArraycontainsObject:per.name]){
if ([[per.name substringToIndex:2]isEqualToString:@"JL"]) {
[self.peripheralsNameArrayaddObject:per.name];
}else {
[self.peripherals removeObject:per];
}
}
}
}
選擇某一搜索到的特定設(shè)備進(jìn)行連接:
LGAlertView *alert= [LGAlertView alertViewWithTitle:@"請選擇您的設(shè)備"
message:@"" style:LGAlertViewStyleActionSheet buttonTitles:self.peripheralsNameArray
cancelButtonTitle:@"取消"destructiveButtonTitle:nil actionHandler:^(LGAlertView *alertView, NSString*title, NSUInteger index) {
CBPeripheral *per;
per = index
self.deviceName = index
[self.bluetoothManagerconnectPeripheral:per options:nil];
此時是中心設(shè)備和外部設(shè)備的連接恐锣,連接成功或者失敗會進(jìn)入不同的方法茅主。
} cancelHandler:^(LGAlertView*alertView) {
[self.bluetoothManagerstopScan];
} destructiveHandler:nil];
}
4、中心設(shè)備與外部設(shè)備連接狀態(tài)調(diào)用的方法:
-(void)centralManager:(CBCentralManager *)centraldidConnectPeripheral:(CBPeripheral *)peripheral(中心設(shè)備和外部設(shè)備的連接成功){
[central stopScan];
//設(shè)置的peripheral委托CBPeripheralDelegate
[peripheral setDelegate:self];
//掃描外設(shè)Services土榴,成功后會進(jìn)入方法:
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError*)error;
[peripheral discoverServices:nil];
}
- (void)centralManager:(CBCentralManager *)central
didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(nullableNSError
*)error;(中心設(shè)備和外部設(shè)備的連接斷開)
- (void)centralManager:(CBCentralManager *)central
didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error ;(中心設(shè)備和外部設(shè)備的連接诀姚,連接失敗)
5玷禽、掃描外設(shè)服務(wù)后緊接著會進(jìn)入服務(wù)的代理方法中:
- (void)peripheral:(CBPeripheral *)peripheraldidDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
for (CBService *service inperipheral.services) {
//掃描每個service的Characteristics赫段,掃描到后會進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral
didDiscoverCharacteristicsForService:(CBService *)service error:(NSError
*)error;
[peripheral discoverCharacteristics:nilforService:service];
}
}
- (void)peripheral:(CBPeripheral *)peripheraldidDiscoverCharacteristicsForService:(CBService *)service error:(NSError*)error{
//獲取Characteristic的值矢赁,讀到數(shù)據(jù)會進(jìn)入方法:-(void)peripheral:(CBPeripheral
*)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic
error:(NSError *)error糯笙;
for (CBCharacteristic*characteristic in service.characteristics){
[peripheralreadValueForCharacteristic:characteristic];
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic*)characteristic error:(NSError *)error {
//打印出characteristic的UUID和值
//!注意,value的類型是NSData撩银,具體開發(fā)時给涕,會根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)
NSLog(@"characteristicuuid:%@value:%@",characteristic.UUID,characteristic.value);
}
6、根據(jù)拿到的數(shù)據(jù)就可以進(jìn)行寫操作:
//寫數(shù)據(jù)
- (void)writeCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic*)characteristic value:(NSData *)value {
//打印出characteristic的權(quán)限蜒蕾,可以看到有很多種,這是一個NS_OPTIONS焕阿,就是可以同時用于好幾個值咪啡,常見的有read,write暮屡,notify撤摸,indicate,知道這幾個基本就夠用了,前連個是讀寫權(quán)限准夷,后兩個都是通知钥飞,兩種不同的通知方式。
/*
typedef NS_OPTIONS(NSUInteger,CBCharacteristicProperties) {
CBCharacteristicPropertyBroadcast= 0x01,
CBCharacteristicPropertyRead= 0x02,
CBCharacteristicPropertyWriteWithoutResponse= 0x04,
CBCharacteristicPropertyWrite= 0x08,
CBCharacteristicPropertyNotify= 0x10,
CBCharacteristicPropertyIndicate= 0x20,
CBCharacteristicPropertyAuthenticatedSignedWrites= 0x40,
CBCharacteristicPropertyExtendedProperties= 0x80,
CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA,6_0)= 0x100,
CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA,6_0)= 0x200
};
*/
//只有characteristic.properties有write的權(quán)限才可以寫
if(characteristic.properties& CBCharacteristicPropertyWrite){
//最好一個type參數(shù)可以為CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,區(qū)別是是否會有反饋
[peripheral writeValue:valueforCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
}
}
7衫嵌、根據(jù)下面方法判斷寫入成功與否:
- (void)peripheral:(CBPeripheral *)peripheraldidWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError*)error;
8读宙、搜索Characteristic的Descriptors,讀到數(shù)據(jù)會進(jìn)入方法:
-(void)peripheral:(CBPeripheral *)peripheraldidDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristicerror:(NSError *)error{
for (CBCharacteristic*characteristic in service.characteristics){
[peripheraldiscoverDescriptorsForCharacteristic:characteristic];
}
}
//搜索到Characteristic的Descriptors
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic*)characteristic error:(NSError *)error
//獲取到Descriptors的值
- (void)peripheral:(CBPeripheral *)peripheraldidUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
//打印出DescriptorsUUID和value
//這個descriptor都是對于characteristic的描述楔绞,一般都是字符串结闸,所以這里我們轉(zhuǎn)換成字符串去解析
NSLog(@"characteristicuuid:%@value:%@",[NSStringstringWithFormat:@"%@",descriptor.UUID],descriptor.value);
}
9、停止并斷開連接設(shè)備:
- (void)disconnectPeripheral:(CBCentralManager *)centralManagerperipheral:(CBPeripheral *)peripheral {
//停止掃描
[centralManager stopScan];
//斷開連接
[centralManagercancelPeripheralConnection:peripheral];
}