ios蓝牙基本使用方法

@implementation ViewController

- (void)viewDidLoad {

   [super viewDidLoad];

   // 蓝牙

   // 1.创建一个蓝牙对象

   self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];

   // 2.进行检索操作

   // nil: 任意的外设

   [self.manager scanForPeripheralsWithServices:nil options:nil];

}

// 如果蓝牙的状态改变的话,就会调用这个方法

// 这个方法一定要实现,要不然会出错.

- (void)centralManagerDidUpdateState:(CBCentralManager *)central;

{

   NSLog(@"蓝牙的状态改变了");

}

// 3.如果发现了蓝牙设备,就会调用这个方法

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;

{

   // 4.连接外设(别的蓝牙设备)

   [self.manager connectPeripheral:peripheral options:0];

}

// 5.连接上某个设备后,调用这个方法

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral

{

   // 6.尝试发现外设的某项服务

   [peripheral discoverServices:nil];

   peripheral.delegate = self;

}

// 7.如果发现某一项服务,就调用这个方法

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(nullable NSError *)error;

{

   if (error) {

       return;

   }

   for (CBService *service in peripheral.services) {

       if ([service.UUID.UUIDString isEqualToString:@"123"]) {

           // 寻找所对应的特征

           [peripheral discoverCharacteristics:nil forService:service];

       }

   }

}

// 8.找到这个服务所组成的特征时,调用这个方法

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error

{

   NSLog(@"可以进行一些通讯操作.传值操作");

}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容