@implementation ViewController
- (void)viewDidLoad {
? ?[super viewDidLoad];
? ?// 藍(lán)牙
? ?// 1.創(chuàng)建一個(gè)藍(lán)牙對象
? ?self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
? ?// 2.進(jìn)行檢索操作
? ?// nil: 任意的外設(shè)
? ?[self.manager scanForPeripheralsWithServices:nil options:nil];
}
// 如果藍(lán)牙的狀態(tài)改變的話,就會調(diào)用這個(gè)方法
// 這個(gè)方法一定要實(shí)現(xiàn),要不然會出錯(cuò).
- (void)centralManagerDidUpdateState:(CBCentralManager *)central;
{
? ?NSLog(@"藍(lán)牙的狀態(tài)改變了");
}
// 3.如果發(fā)現(xiàn)了藍(lán)牙設(shè)備,就會調(diào)用這個(gè)方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
{
? ?// 4.連接外設(shè)(別的藍(lán)牙設(shè)備)
? ?[self.manager connectPeripheral:peripheral options:0];
}
// 5.連接上某個(gè)設(shè)備后,調(diào)用這個(gè)方法
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
? ?// 6.嘗試發(fā)現(xiàn)外設(shè)的某項(xiàng)服務(wù)
? ?[peripheral discoverServices:nil];
? ?peripheral.delegate = self;
}
// 7.如果發(fā)現(xiàn)某一項(xiàng)服務(wù),就調(diào)用這個(gè)方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error;
{
? ?if (error) {
? ? ? ?return;
? ?}
? ?for (CBService *service in peripheral.services) {
? ? ? ?if ([service.UUID.UUIDString isEqualToString:@"123"]) {
? ? ? ? ? ?// 尋找所對應(yīng)的特征
? ? ? ? ? ?[peripheral discoverCharacteristics:nil forService:service];
? ? ? ?}
? ?}
}
// 8.找到這個(gè)服務(wù)所組成的特征時(shí),調(diào)用這個(gè)方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
? ?NSLog(@"可以進(jìn)行一些通訊操作.傳值操作");
}
@end