iOS關(guān)于CoreBluetooth的簡單使用

第一步,先創(chuàng)建一個(gè)中心設(shè)備

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBCentralManagerDelegate,CBPeripheralDelegate>
@property (nonatomic,strong) CBCentralManager *myCentralManager;
@property (nonatomic,strong) CBPeripheral *myPeripheral;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
#pragma mark 1 Starting Up a Central Manager(啟動(dòng)一個(gè)Central Manager)
    //這里的queue如果為nil就會(huì)在主線程
    self.myCentralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];   
}

第二步,掃描外設(shè)

#pragma mark 2 掃描外設(shè)(discover),掃描外設(shè)的方法我們放在centralManager成功打開的委托中,因?yàn)橹挥性O(shè)備成功打開,才能開始掃描,否則會(huì)報(bào)錯(cuò)。
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    //開始掃描周圍的外設(shè)
    if(central.state == CBCentralManagerStatePoweredOn)
    {
        //第一個(gè)參數(shù)nil就是掃描周圍所有的外設(shè)
        [self.myCentralManager scanForPeripheralsWithServices:nil options:nil];
    }
}

第三步 連接外設(shè)(connect)

#pragma mark 3 連接外設(shè)(connect)
//掃描到設(shè)備會(huì)進(jìn)入方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
 
    NSLog(@"當(dāng)掃描到設(shè)備:%@",peripheral.name);
    
    //這里自己去設(shè)置下連接規(guī)則,我設(shè)置的是8結(jié)尾的設(shè)備
    if([peripheral.name hasSuffix:@"8"])
    {//一個(gè)主設(shè)備最多能連7個(gè)外設(shè),每個(gè)外設(shè)最多只能給一個(gè)主設(shè)備連接,連接成功,失敗,斷開會(huì)進(jìn)入各自的委托
        //停止搜索
        [self.myCentralManager stopScan];
      
        //這里先將peripheral值保存一下,有時(shí)會(huì)自動(dòng)銷毀導(dǎo)致連接不上
        self.myPeripheral = peripheral;
        //連接外設(shè)
        [self.myCentralManager connectPeripheral:self.myPeripheral options:nil];
        
    }
}

//連接到Peripherals-失敗
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"===>>>連接到名稱為(%@)的設(shè)備-失敗,原因:%@",[peripheral name],[error localizedDescription]);
}

//Peripherals斷開連接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"===>>>外設(shè)連接斷開連接 %@: %@\n", [peripheral name], [error localizedDescription]);
}

第四步 掃描外設(shè)中的服務(wù)和特征(discover)

#pragma mark 4 掃描外設(shè)中的服務(wù)和特征(discover)

//連接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"===>>>連接到名稱為(%@)的設(shè)備-成功",peripheral.name);
    //設(shè)置的peripheral委托CBPeripheralDelegate
    [peripheral setDelegate:self];

    //掃描外設(shè)Services
    [peripheral discoverServices:nil];
}


//掃描到Services
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    NSLog(@"===>>>掃描到服務(wù):%@",peripheral.services);
    if (error)
    {
        NSLog(@"===>>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    for (CBService *service in peripheral.services)
    {
        NSLog(@"%@",service.UUID);
        //掃描每個(gè)service的Characteristics
        [peripheral discoverCharacteristics:nil forService:service];
    }
}

第五步 與外設(shè)做數(shù)據(jù)交互

#pragma mark 5 與外設(shè)做數(shù)據(jù)交互
//掃描到Characteristics
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error)
    {
        NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        NSLog(@"service:%@ 的 Characteristic: %@",service.UUID,characteristic.UUID);
    }
    //獲取Characteristic的值
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        [peripheral readValueForCharacteristic:characteristic];
    }
    //搜索Characteristic的Descriptors
    for (CBCharacteristic *characteristic in service.characteristics)
    {
        [peripheral discoverDescriptorsForCharacteristic:characteristic];
    }
}


//獲取的charateristic的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    //打印出characteristic的UUID和值
    //!注意,value的類型是NSData,具體開發(fā)時(shí),會(huì)根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)
    NSLog(@"characteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
    //寫入數(shù)據(jù)到外設(shè)中
//    [self.myPeripheral writeValue:<#(nonnull NSData *)#> forCharacteristic:<#(nonnull CBCharacteristic *)#> type:<#(CBCharacteristicWriteType)#>]
    
}

//搜索到Characteristic的Descriptors
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    //打印出Characteristic和他的Descriptors
    NSLog(@"characteristic uuid:%@",characteristic.UUID);
    for (CBDescriptor *d in characteristic.descriptors) {
        NSLog(@"Descriptor uuid:%@",d.UUID);
    }
}

//獲取到Descriptors的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{
    //打印出DescriptorsUUID 和value
    //這個(gè)descriptor都是對(duì)于characteristic的描述,一般都是字符串,所以這里我們轉(zhuǎn)換成字符串去解析
    NSLog(@"characteristic uuid:%@  value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
    //寫入數(shù)據(jù)到外設(shè)中
//    [self.myPeripheral writeValue:<#(nonnull NSData *)#> forDescriptor:<#(nonnull CBDescriptor *)#>]
}

Demo地址在這里

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 這里我們具體說明一下中心模式的應(yīng)用場景。主設(shè)備(手機(jī)去掃描連接外設(shè),發(fā)現(xiàn)外設(shè)服務(wù)和屬性,操作服務(wù)和屬性的應(yīng)用。一般...
    丶逝水流年閱讀 2,411評(píng)論 3 4
  • (一) iOS藍(lán)牙開發(fā)藍(lán)牙相關(guān)基礎(chǔ)知識(shí) 藍(lán)牙常見名稱和縮寫 MFI ======= make for ipad ...
    雷鳴1010閱讀 5,132評(píng)論 2 12
  • 本文出自: http://mokai.me/bluetooth-guide.html 藍(lán)牙技術(shù),很早以前就被有了...
    _GKK_閱讀 1,418評(píng)論 0 3
  • 曾經(jīng)看過一篇文章,大概意思是說如何改變文藝女青年。改變她們的矯情,改變她們的煽情,改變她們的個(gè)性,改變她們的一切。...
    Cassy張閱讀 1,310評(píng)論 2 3
  • 不知是離開中國后的第幾場雪了,她站在偌大的窗前,雪花漫天飛舞?!霸撟吡??!彼p聲的說到,平日里大小正好的尾戒好...
    珊Double74839閱讀 411評(píng)論 0 0

友情鏈接更多精彩內(nèi)容