CoreBluetooth

  • BLE:(Bluetooth low energy)藍(lán)牙4.0設(shè)備因?yàn)榈秃碾?也叫BLE
  • peripheral,central:外設(shè)和中心設(shè)備,發(fā)起鏈接的是central(一般是指手機(jī)),被鏈接的設(shè)備是peripheral(運(yùn)動(dòng)手環(huán))
  • service and characteristic:(服務(wù)和特征)每個(gè)設(shè)備會(huì)提供服務(wù)和特征,類似于服務(wù)端的API,但是結(jié)構(gòu)不同.每個(gè)設(shè)備會(huì)有很多服務(wù),每個(gè)服務(wù)中包含很多字段,這些字段的權(quán)限一般分為讀(read),寫(write),通知(notify)幾種,就是我們連接設(shè)備后具體需要操作的內(nèi)容
  • Description:每個(gè)characteristic可以對(duì)應(yīng)一個(gè)或者多個(gè)Description用于描述characteristic的信息或?qū)傩?eg.范圍,計(jì)量單位)
  • 這兩組api粉筆對(duì)應(yīng)不同的業(yè)務(wù)常見:左側(cè)叫中心模式,就是以你的app作為中心,連接其他的外設(shè)的場(chǎng)景;而右側(cè)稱為外設(shè)模式,使用手機(jī)作為外設(shè)
    連接其他中心設(shè)備操作的場(chǎng)景

  • 服務(wù)和特征(service and characteristic)

    • 每個(gè)設(shè)備都會(huì)有1個(gè)or多個(gè)服務(wù)
    • 每個(gè)服務(wù)里都會(huì)有1個(gè)or多個(gè)特征
    • 特征就是具體鍵值對(duì),提供數(shù)據(jù)的地方
    • 每個(gè)特征屬性分為:讀,寫,通知等等
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};
  • 外設(shè),服務(wù),特征的關(guān)系


    外設(shè),服務(wù),特征的關(guān)系



BLE中心模式流程

  • 1.建立中心角色
  • 2.掃描外設(shè)(Discover Peripheral)
  • 3.連接外設(shè)(Connect Peripheral)
  • 4.掃描外設(shè)中的服務(wù)和特征(Discover Services And Characteristics)
    • 4.1 獲取外設(shè)的services
    • 4.2 獲取外設(shè)的Characteristics,獲取characteristics的值,,獲取Characteristics的Descriptor和Descriptor的值
  • 5.利用特征與外設(shè)做數(shù)據(jù)交互(Explore And Interact)
  • 6.訂閱Characteristic的通知
  • 7.斷開連接(Disconnect)

BLE外設(shè)模式流程

  • 1.啟動(dòng)一個(gè)Peripheral管理對(duì)象
  • 2.本地peripheral設(shè)置服務(wù),特征,描述,權(quán)限等等
  • 3.peripheral發(fā)送廣告
  • 4.設(shè)置處理訂閱,取消訂閱,讀characteristic,寫characteristic的代理方法

藍(lán)牙設(shè)備的狀態(tài)

  • 1.待機(jī)狀態(tài)(standby):設(shè)備沒有傳輸和發(fā)送數(shù)據(jù),并且沒有連接到任何外設(shè)
  • 2.廣播狀態(tài)(Advertiser):周期性廣播狀態(tài)
  • 3.掃描狀態(tài)(Scanner):主動(dòng)搜索正在廣播的設(shè)備
  • 4.發(fā)起鏈接狀態(tài)(Initiator):主動(dòng)向掃描設(shè)備發(fā)起連接
  • 5.主設(shè)備(Master):作為主設(shè)備連接到其它設(shè)備.
  • 6.從設(shè)備(Slave):作為從設(shè)備鏈接到其它設(shè)備

藍(lán)牙設(shè)備的五種工作狀態(tài)

  • 準(zhǔn)備(Standby)
  • 廣播(Advertising)
  • 監(jiān)聽掃描(Scanning)
  • 發(fā)起連接(Initiating)
  • 已連接(Connected)

藍(lán)牙和版本使用限制

  • 藍(lán)牙2.0:越獄設(shè)備
  • BLE:iOS6以上
  • MFI認(rèn)證設(shè)備:無限制



代碼實(shí)現(xiàn):

實(shí)現(xiàn)步驟:

一、BLE中心模式流程

  • 1.建立中心角色
  • 2.掃描外設(shè)(Discover Peripheral)
  • 3.連接外設(shè)(Connect Peripheral)
  • 4.掃描外設(shè)中的服務(wù)和特征(Discover Services And Characteristics)
    • 4.1 獲取外設(shè)的services
    • 4.2 獲取外設(shè)的Characteristics,獲取characteristics的值,,獲取Characteristics的Descriptor和Descriptor的值
  • 5.利用特征與外設(shè)做數(shù)據(jù)交互(Explore And Interact)
  • 6.訂閱Characteristic的通知
  • 7.斷開連接(Disconnect)

1.導(dǎo)入CB頭文件,建立主設(shè)備管理類,設(shè)置主設(shè)備代理

#import <CoreBluetooth/CoreBluetooth.h>
@interface XMGBLEController () <CBCentralManagerDelegate>
@property (nonatomic, strong) CBCentralManager *cMgr; /**< 中心管理設(shè)備 */
@end
@implementation XMGBLEController
#pragma mark - 懶加載
// 1.建立中心管理者
- (CBCentralManager *)cMgr
{
    if (!_cMgr) {
        NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
        /*
         設(shè)置主設(shè)備的代理,CBCentralManagerDelegate
         必須實(shí)現(xiàn)的:
         - (void)centralManagerDidUpdateState:(CBCentralManager *)central;//主設(shè)備狀態(tài)改變調(diào)用,在初始化CBCentralManager的適合會(huì)打開設(shè)備,只有當(dāng)設(shè)備正確打開后才能使用
         其他選擇實(shí)現(xiàn)的委托中比較重要的:
         - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI; //找到外設(shè)
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開外設(shè)
         */
        _cMgr = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; // 線程不傳默認(rèn)是主線程
    }
    return _cMgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"BLE";
    self.view.backgroundColor = [UIColor orangeColor];
    // 初始化
    [self cMgr];
    // 不能在此處掃描,因?yàn)闋顟B(tài)還沒變?yōu)榇蜷_
    //[self.cMgr scanForPeripheralsWithServices:nil options:nil];
}

2.掃描外設(shè)

  • 掃描的方法防治cMgr成功打開的代理方法中
  • 只有設(shè)備成功打開,才能開始掃描,否則會(huì)報(bào)錯(cuò)
#pragma mark - CBCentralManagerDelegate
// 中心管理者狀態(tài)改變, 在初始化CBCentralManager的時(shí)候會(huì)打開設(shè)備,只有當(dāng)設(shè)備正確打開后才能使用
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            // 2.開始掃描周圍的外設(shè)
            /*
             第一個(gè)參數(shù)nil就是掃描周圍所有的外設(shè),掃描到外設(shè)后會(huì)進(jìn)入
             - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
             */
            [self.cMgr scanForPeripheralsWithServices:nil options:nil];
            break;
        default:
        break;
    }
}
// 掃描到設(shè)備會(huì)進(jìn)入到此代理方法
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);
    // 接下來連接設(shè)備
}

3.連接外設(shè)

  • 掃描手環(huán),打印結(jié)果 圖


    Paste_Image.png
  • 根據(jù)打印結(jié)果

// 掃描到設(shè)備會(huì)進(jìn)入到此代理方法
-(void)centralManager:(CBCentralManager *)central didDisco verPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"%s, line = %d, per = %@, data = %@, rssi = %@", __FUNCTION__, __LINE__, peripheral, advertisementData, RSSI);

    // 3.接下來可以連接設(shè)備
    //如果你沒有設(shè)備,可以下載一個(gè)app叫l(wèi)ightbule的app去模擬一個(gè)設(shè)備
    //這里自己去設(shè)置下連接規(guī)則,我設(shè)置的是二維碼掃描到的運(yùn)動(dòng)手環(huán)的設(shè)備號(hào)
    // 判斷設(shè)備號(hào)是否掃描到
    if ([peripheral.name isEqualToString:@"OBand-75"]) {
        /*
         一個(gè)主設(shè)備最多能連7個(gè)外設(shè),每個(gè)外設(shè)最多只能給一個(gè)主設(shè)備連接,連接成功,失敗,斷開會(huì)進(jìn)入各自的委托
         - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//連接外設(shè)成功的委托
         - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外設(shè)連接失敗的委托
         - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//斷開外設(shè)的委托
         */
        // 保存外設(shè),否則方法結(jié)束就銷毀
        self.per = peripheral;
        [self.cMgr connectPeripheral:self.per options:nil];
    }else
    {
        // 此處Alert提示未掃描到設(shè)備,重新掃描
#warning noCode
        NSLog(@"沒掃描到 >>>>>>>>  %s, line = %d", __FUNCTION__, __LINE__);
    }
}
// 外設(shè)連接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>連接到名稱為(%@)的設(shè)備-成功",peripheral.name);
}
// 外設(shè)連接失敗
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}
// 斷開連接(丟失連接)
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}

4.掃描外設(shè)中的服務(wù)和特征

設(shè)備鏈接成功后,就可以掃描設(shè)備的服務(wù)(services)了,同樣是通過代理,掃描到結(jié)果后會(huì)觸發(fā)某代理方法.
注意:此時(shí)CBCentralManagerDelegate已經(jīng)不能滿足需求,需要新的CBPeripheralDelegate來搞定.
該協(xié)議中包含了central與peripheral的許多回調(diào)方法
(eg.:獲取services,獲取characteristics,獲取characteristics的值,獲取characteristics的Descriptor以及Descriptor的值,寫數(shù)據(jù),讀RSSI,用通知的方式訂閱數(shù)據(jù)等等).

  • 4.1 獲取外設(shè)的services
    • 首先設(shè)置外設(shè)的代理,并搜尋services
    • 然后在代理方法peripheral:didDiscoverServices:中遍歷services
// 外設(shè)連接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    NSLog(@">>>連接到名稱為(%@)的設(shè)備-成功",peripheral.name);
    //設(shè)置的peripheral代理CBPeripheralDelegate
    //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
    [peripheral setDelegate:self];

    //掃描外設(shè)Services,成功后會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    [peripheral discoverServices:nil];
    /*
     Discovers the specified services of the peripheral.
     An array of CBUUID objects that you are interested in. Here, each CBUUID object represents a UUID that identifies the type of service you want to discover.
     */
}

#pragma mark - CBPeripheralDelegate
// 發(fā)現(xiàn)外設(shè)的service
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error)
    {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }

    for (CBService *service in peripheral.services) {
        NSLog(@"service.UUID = %@", service.UUID);
        //掃描每個(gè)service的Characteristics,掃描到后會(huì)進(jìn)入方法: -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
4.2 獲取外設(shè)的characteris,獲取Characteristics的值,獲取Characteristics的Descriptor以及Descriptor的值
// 外設(shè)發(fā)現(xiàn)service的特征
- (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);
    }

#warning noCodeFor 優(yōu)化,分開寫是為了讓大家看注釋清晰,并不符合編碼規(guī)范
    //獲取Characteristic的值,讀到數(shù)據(jù)會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral readValueForCharacteristic:characteristic]; // 外設(shè)讀取特征的值
    }

    //搜索Characteristic的Descriptors,讀到數(shù)據(jù)會(huì)進(jìn)入方法:-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
    for (CBCharacteristic *characteristic in service.characteristics){
        [peripheral discoverDescriptorsForCharacteristic:characteristic]; // 外設(shè)發(fā)現(xiàn)特征的描述
    }
}

// 獲取characteristic的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    //打印出characteristic的UUID和值
    //!注意,value的類型是NSData,具體開發(fā)時(shí),會(huì)根據(jù)外設(shè)協(xié)議制定的方式去解析數(shù)據(jù)
    NSLog(@"%s, line = %d, characteristic.UUID:%@  value:%@", __FUNCTION__, __LINE__, characteristic.UUID, characteristic.value);
}
// 獲取Characteristics的 descriptor的值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(nonnull CBDescriptor *)descriptor error:(nullable NSError *)error
{
    //打印出DescriptorsUUID 和value
    //這個(gè)descriptor都是對(duì)于characteristic的描述,一般都是字符串,所以這里我們轉(zhuǎn)換成字符串去解析
    NSLog(@"%s, line = %d, descriptor.UUID:%@ value:%@", __FUNCTION__, __LINE__, descriptor.UUID, descriptor.value);
}
// 發(fā)現(xiàn)特征Characteristics的描述Descriptor
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(nonnull CBCharacteristic *)characteristic error:(nullable NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    for (CBDescriptor *descriptor in characteristic.descriptors) {
        NSLog(@"descriptor.UUID:%@",descriptor.UUID);
    }
}

5.寫數(shù)據(jù)到特征中

// 5.將數(shù)據(jù)寫入特征(自定義方法,為了看的更清楚,沒別的意思)
- (void)yf_peripheral:(CBPeripheral *)peripheral writeData:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic
{
    /*
    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
    };
     打印出特征的權(quán)限(characteristic.properties),可以看到有很多種,這是一個(gè)NS_OPTIONS的枚舉,可以是多個(gè)值
     常見的又read,write,noitfy,indicate.知道這幾個(gè)基本夠用了,前倆是讀寫權(quán)限,后倆都是通知,倆不同的通知方式
     */
    NSLog(@"%s, line = %d, characteristic.properties:%d", __FUNCTION__, __LINE__, characteristic.properties);

    // 只有特征的properties中有寫的屬性時(shí)候,才寫
    if (characteristic.properties & CBCharacteristicPropertyWrite) {
        // 這句才是正宗的核心代碼
        [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }
}

6.訂閱特征的通知

// 設(shè)置通知
- (void)yf_peripheral:(CBPeripheral *)peripheral setNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    // 設(shè)置通知, 數(shù)據(jù)會(huì)進(jìn)入 peripheral:didUpdateValueForCharacteristic:error:方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
// 取消通知
- (void)yf_peripheral:(CBPeripheral *)peripheral cancelNotifyForCharacteristic:(CBCharacteristic *)characteristic
{
    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}

7.斷開連接

// 7.斷開連接
- (void)yf_cMgr:(CBCentralManager *)cMgr stopScanAndDisConnectWithPeripheral:(CBPeripheral *)peripheral
{
    // 停止掃描
    [cMgr stopScan];
    // 斷開連接
    [cMgr cancelPeripheralConnection:peripheral];
}


二、peripheral模式的流程

  • 1.引入CoreBluetooth框架,初始化peripheralManager
  • 2.設(shè)置peripheralManager中的內(nèi)容
  • 3.開啟廣播advertising
  • 4.對(duì)central的操作進(jìn)行響應(yīng)
    • 4.1 讀characteristics請(qǐng)求
    • 4.2 寫characteristics請(qǐng)求
    • 4.3 訂閱和取消訂閱characteristics

1.引入CoreBluetooth框架,初始化peripheralManager

#import <CoreBluetooth/CoreBluetooth.h>@interface XMGBLEPeripheralViewController () <CBPeripheralManagerDelegate>
@property (nonatomic, strong) CBPeripheralManager *pMgr; /**< 外設(shè)管理者 */
@end

@implementation XMGBLEPeripheralViewController
// 懶加載
- (CBPeripheralManager *)pMgr{ if (!_pMgr) { 
        _pMgr = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()]; 
    }
    return  _pMgr;
}

- (void)viewDidLoad {
    [super viewDidLoad]; 
   // 調(diào)用get方法初始化,初始化后CBPeripheralManager狀態(tài)改變會(huì)調(diào)用代理方法peripheralManagerDidUpdateState: 
   // 模擬器永遠(yuǎn)也不會(huì)是CBPeripheralManagerStatePoweredOn狀態(tài) 
   [self pMgr];
}

2.設(shè)置peripheralManager中的內(nèi)容

  • 創(chuàng)建characteristics及其description,
  • 創(chuàng)建service,把characteristics添加到service中,
  • 再把service添加到peripheralManager中
#pragma mark - CBPeripheralManagerDelegate
// CBPeripheralManager初始化后會(huì)觸發(fā)的方法
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{
  if (peripheral.state == CBPeripheralManagerStatePoweredOn)         
  { 
    // 提示設(shè)備成功打開
    [SVProgressHUD showSuccessWithStatus:@"xmg設(shè)備打開成功~"];
    // 配置各種服務(wù)入CBPeripheralManager
    [self yf_setupPMgr]; }else { // 提示設(shè)備打開失敗   
    [SVProgressHUD showErrorWithStatus:@"失敗!"]; 
  }
}

#pragma mark - 私有方法
- (void)yf_setupPMgr{
  // 特征描述的UUID 
  CBUUID *characteristicUserDescriptionUUID = [CBUUID UUIDWithString:CBUUIDCharacteristicUserDescriptionString];
  // 特征的通知UUID 
  CBUUID *notifyCharacteristicUUID = [CBUUID UUIDWithString:notiyCharacteristicStrUUID]; 
  // 特征的讀寫UUID
  CBUUID *readwriteCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID]; 
  // 特征的只讀UUID 
  CBUUID *readCharacteristicUUID = [CBUUID UUIDWithString:readwriteCharacteristicStrUUID];
   CBUUID *ser1UUID = [CBUUID UUIDWithString:Service1StrUUID];
   CBUUID *ser2UUID = [CBUUID UUIDWithString:Service2StrUUID]; 
  // 初始化一個(gè)特征的描述 
  CBMutableDescriptor *des1 = [[CBMutableDescriptor alloc] initWithType:characteristicUserDescriptionUUID value:@"xmgDes1"]; 
  // 可通知的特征 
  CBMutableCharacteristic *notifyCharacteristic = [[CBMutableCharacteristic alloc] 
          initWithType:notifyCharacteristicUUID // UUID 
          properties:CBCharacteristicPropertyNotify // 枚舉:通知 
          value:nil // 數(shù)據(jù)先不傳 
          permissions:CBAttributePermissionsReadable]; // 枚舉:可讀
  // 可讀寫的特征 
  CBMutableCharacteristic *readwriteChar = [[CBMutableCharacteristic alloc] 
          initWithType:readwriteCharacteristicUUID       
          properties:CBCharacteristicPropertyRead | CBCharacteristicPropertyWrite 
          value:nil 
          permissions:CBAttributePermissionsReadable | CBAttributePermissionsWriteable];
   [readwriteChar setDescriptors:@[des1]]; 
  // 設(shè)置特征的描述
 // 只讀特征 
  CBMutableCharacteristic *readChar = [[CBMutableCharacteristic alloc] 
          initWithType:readCharacteristicUUID 
          properties:CBCharacteristicPropertyRead 
          value:nil 
          permissions:CBAttributePermissionsReadable]; 
   // 初始化服務(wù)1
  CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES]; 
  // 為服務(wù)設(shè)置倆特征(通知, 帶描述的讀寫) 
  [ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]]; 
  // 初始化服務(wù)2,并且添加一個(gè)只讀特征 CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES]; 
  ser2.characteristics = @[readChar]; 
  // 添加服務(wù)進(jìn)外設(shè)管理者 
  // 添加操作會(huì)觸發(fā)代理方法peripheralManager:didAddService:error:
   [self.pMgr addService:ser1];
   [self.pMgr addService:ser2];}

3.開啟廣播

// 添加服務(wù)進(jìn)CBPeripheralManager時(shí)會(huì)觸發(fā)的方法
- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{
   // 由于添加了兩次ser,所以方法會(huì)調(diào)用兩次 static int i = 0; 
  if (!error) { i++; } 
  // 當(dāng)?shù)诙芜M(jìn)入方法時(shí)候,代表兩個(gè)服務(wù)添加完畢,此時(shí)要用到2,由于沒有擴(kuò)展性,所以新增了可變數(shù)組,記錄添加的服務(wù)數(shù)量
   if (i == self.servieces.count) { 
      // 廣播內(nèi)容 
      NSDictionary *advertDict = @{CBAdvertisementDataServiceUUIDsKey: [self.servieces valueForKeyPath:@"UUID"], CBAdvertisementDataLocalNameKey:LocalNameKey
    }; 
    // 發(fā)出廣播,會(huì)觸發(fā)peripheralManagerDidStartAdvertising:error: 
    [peripheral startAdvertising:advertDict]; 
  }}
  // 開始廣播觸發(fā)的代理
- (void)peripheralManagerDidStartAdvertising:(CBPeripheralManager *)peripheral error:(NSError *)error{
}

>>>>>>>>分割線>>>>下面是修改的地方

@property (nonatomic, strong) NSMutableArray *servieces; /**< 服務(wù)可變數(shù)組 */

// 自定義服務(wù)
- (NSMutableArray *)servieces{
     if (!_servieces) 
     {
           _servieces = [NSMutableArray array]; 
      }
   return _servieces;
}
#pragma mark - 私有方法
- (void)yf_setupPMgr
{
   ... 
  // 初始化服務(wù)1
   CBMutableService *ser1 = [[CBMutableService alloc] initWithType:ser1UUID primary:YES];
  // 為服務(wù)設(shè)置倆特征(通知, 帶描述的讀寫)
   [ser1 setCharacteristics:@[notifyCharacteristic, readwriteChar]]; 
  [self.servieces addObject:ser1]; 
  // 初始化服務(wù)2,并且添加一個(gè)只讀特征
  CBMutableService *ser2 = [[CBMutableService alloc] initWithType:ser2UUID primary:YES];
   ser2.characteristics = @[readChar]; [self.servieces addObject:ser2]; 
  // 添加服務(wù)進(jìn)外設(shè)管理者 
  // 添加操作會(huì)觸發(fā)代理方法peripheralManager:didAddService:error:
   if (self.servieces.count) { 
      for (CBMutableService *ser in self.servieces) {
         [self.pMgr addService:ser];
       }
   }
};

4.對(duì)central的操作做出響應(yīng)

  • 4.1 讀characteristics請(qǐng)求
  • 4.2 寫characteristics請(qǐng)求
  • 4.3 訂閱和取消訂閱characteristics
// 外設(shè)收到讀的請(qǐng)求,然后讀特征的值賦值給request
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request{ 
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__); 
    // 判斷是否可讀
     if (request.characteristic.properties & CBCharacteristicPropertyRead) {
       NSData *data = request.characteristic.value; request.value = data;
       // 對(duì)請(qǐng)求成功做出響應(yīng) 
       [self.pMgr respondToRequest:request withResult:CBATTErrorSuccess]; 
    }else { 
       [self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted]; 
  }
}

// 外設(shè)收到寫的請(qǐng)求,然后讀request的值,寫給特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests{
     NSLog(@"%s, line = %d, requests = %@", __FUNCTION__, __LINE__, requests);
     CBATTRequest *request = requests.firstObject;
     if (request.characteristic.properties & CBCharacteristicPropertyWrite) {
         NSData *data = request.value; 
        // 此處賦值要轉(zhuǎn)類型,否則報(bào)錯(cuò) 
        CBMutableCharacteristic *mChar = (CBMutableCharacteristic *)request.characteristic;   
        mChar.value = data; 
       // 對(duì)請(qǐng)求成功做出響應(yīng) 
       [self.pMgr respondToRequest:request withResult:CBATTErrorSuccess];
     }else { 
        [self.pMgr respondToRequest:request withResult:CBATTErrorWriteNotPermitted];
     }
}

// 與CBCentral的交互
// 訂閱特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{ 
    NSLog(@"%s, line = %d, 訂閱了%@的數(shù)據(jù)", __FUNCTION__, __LINE__, characteristic.UUID); 
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(yf_sendData:) userInfo:characteristic repeats:YES];
     self.timer = timer; 
    /* 另一種方法 */
    // NSTimer *testTimer = [NSTimer timerWithTimeInterval:2.0// target:self// selector:@selector(yf_sendData:)// userInfo:characteristic// repeats:YES];// [[NSRunLoop currentRunLoop] addTimer:testTimer forMode:NSDefaultRunLoopMode];}
// 取消訂閱特征
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{
     NSLog(@"%s, line = %d, 取消訂閱了%@的數(shù)據(jù)", __FUNCTION__, __LINE__, characteristic.UUID); [self.timer invalidate]; 
    self.timer = nil;
}
- (void)peripheralManagerIsReadyToUpdateSubscribers:(CBPeripheralManager *)peripheral{ 
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
}

// 計(jì)時(shí)器每隔兩秒調(diào)用的方法
- (BOOL)yf_sendData:(NSTimer *)timer{ 
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      dateFormatter.dateFormat = @"yy:MM:dd:HH:mm:ss"; 
      NSString *now = [dateFormatter stringFromDate:[NSDate date]];
      NSLog(@"now = %@", now); 
      // 執(zhí)行回應(yīng)central通知數(shù)據(jù)     
     return [self.pMgr updateValue:[now dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:timer.userInfo onSubscribedCentrals:nil];
}



  • github

項(xiàng)目 簡介
MGDS_Swif 逗視視頻直播
MGMiaoBo 喵播視頻直播
MGDYZB 斗魚視頻直播
MGDemo n多小功能合集
MGBaisi 高度仿寫百思
MGSinaWeibo 高度仿寫Sina
MGLoveFreshBeen 一款電商App
MGWeChat 小部分實(shí)現(xiàn)微信功能
MGTrasitionPractice 自定義轉(zhuǎn)場(chǎng)練習(xí)
DBFMDemo 豆瓣電臺(tái)
MGPlayer 一個(gè)播放視頻的Demo
MGCollectionView 環(huán)形圖片排布以及花瓣形排布
MGPuBuLiuDemo 瀑布流--商品展
MGSlideViewDemo 一個(gè)簡單點(diǎn)的側(cè)滑效果,仿QQ側(cè)滑
MyResume 一個(gè)展示自己個(gè)人簡歷的Demo
GoodBookDemo 好書
Snip20161026_15.png

Snip20161026_16.png

Snip20161026_35.png
逗視介紹1.gif

逗視介紹2.gif

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,786評(píng)論 6 534
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,656評(píng)論 3 419
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,697評(píng)論 0 379
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,098評(píng)論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,855評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,254評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,322評(píng)論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,473評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,014評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,833評(píng)論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,016評(píng)論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,568評(píng)論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,273評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,680評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,946評(píng)論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,730評(píng)論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,006評(píng)論 2 374

推薦閱讀更多精彩內(nèi)容