蓝牙

转载请注明出处ios

http://blog.csdn.net/pony_maggie/article/details/26740237
编程


做者:小马xcode


IOS学习也一段时间了,该上点干货了。前段时间研究了一下IOS蓝牙通信相关的东西,把研究的一个成果给你们分享一下。app

 

一 项目背景框架

简单介绍一下作的东西,设备是一个金融刷卡器,经过蓝牙与iphone手机通信。手机端的app经过发送不一样的指令(经过蓝牙)控制刷卡器执行一些动做,好比读磁条卡,读金融ic卡等。上几张图容易理解一些:iphone

 


            

 

看了上面几张图,你应该大概了解这是个什么东东了。函数

 

二 IOS 蓝牙介绍oop

 

蓝牙协议自己经历了从1.0到4.0的升级演变, 最新的4.0以其低功耗著称,因此通常也叫BLE(Bluetoothlow energy)。学习

 

iOS 有两个框架支持蓝牙与外设链接。一个是 ExternalAccessory。从ios3.0就开始支持,也是在iphone4s出来以前用的比较多的一种模式,可是它有个很差的地方,External Accessory须要拿到苹果公司的MFI认证。测试

 

另外一个框架则是本文要介绍的CoreBluetooth,在iphone4s开始支持,专门用于与BLE设备通信(由于它的API都是基于BLE的)。这个不须要MFI,而且如今不少蓝牙设备都支持4.0,因此也是在IOS比较推荐的一种开发方法。

 

三 CoreBluetooth介绍

 

CoreBluetooth框架的核心实际上是两个东西,peripheral和central, 能够理解成外设和中心。对应他们分别有一组相关的API和类,以下图所示:

 

 

 若是你要编程的设备是central那么你大部分用到,反之亦然。在咱们这个示例中,金融刷卡器是peripheral,咱们的iphone手机 是central,因此我将大部分使用上图中左边部分的类。使用peripheral编程的例子也有不少,好比像用一个ipad和一个iphone通 讯,ipad能够认为是central,iphone端是peripheral,这种状况下在iphone端就要使用上图右边部分的类来开发了。

 

四 服务和特征

 

有个概念有必要先说明一下。什么是服务和特征呢(service and characteristic)?

 

每一个蓝牙4.0的设备都是经过服务和特征来展现本身的,一个设备必然包含一个或多个服务,每一个服务下面又包含若干个特征。特征是与外界交互的最小单位。好比说,一台蓝牙4.0设备,用特征A来描述本身的出厂信息,用特征B来与收发数据等。

 

服务和特征都是用UUID来惟一标识的,UUID的概念若是不清楚请自行google,国际蓝牙组织为一些很典型的设备(好比测量心跳和血压的设备)规定了标准的service UUID(特征的UUID比较多,这里就不列举了),以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1.    
  2. #define      BLE_UUID_ALERT_NOTIFICATION_SERVICE   0x1811  
  3.  #define     BLE_UUID_BATTERY_SERVICE   0x180F  
  4.  #define     BLE_UUID_BLOOD_PRESSURE_SERVICE   0x1810  
  5.  #define     BLE_UUID_CURRENT_TIME_SERVICE   0x1805  
  6.  #define     BLE_UUID_CYCLING_SPEED_AND_CADENCE   0x1816  
  7.  #define     BLE_UUID_DEVICE_INFORMATION_SERVICE   0x180A  
  8.  #define     BLE_UUID_GLUCOSE_SERVICE   0x1808  
  9.  #define     BLE_UUID_HEALTH_THERMOMETER_SERVICE   0x1809  
  10.  #define     BLE_UUID_HEART_RATE_SERVICE   0x180D  
  11.  #define     BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE   0x1812  
  12.  #define     BLE_UUID_IMMEDIATE_ALERT_SERVICE   0x1802  
  13.  #define     BLE_UUID_LINK_LOSS_SERVICE   0x1803  
  14.  #define     BLE_UUID_NEXT_DST_CHANGE_SERVICE   0x1807  
  15.  #define     BLE_UUID_PHONE_ALERT_STATUS_SERVICE   0x180E  
  16.  #define     BLE_UUID_REFERENCE_TIME_UPDATE_SERVICE   0x1806  
  17.  #define     BLE_UUID_RUNNING_SPEED_AND_CADENCE   0x1814  
  18.  #define     BLE_UUID_SCAN_PARAMETERS_SERVICE   0x1813  
  19.  #define     BLE_UUID_TX_POWER_SERVICE   0x1804  
  20.  #define     BLE_UUID_CGM_SERVICE   0x181A  


 

固然还有不少设备并不在这个标准列表里,好比我用的这个金融刷卡器。蓝牙设备硬件厂商一般都会提供他们的设备里面各个服务(service)和特征(characteristics)的功能,好比哪些是用来交互(读写),哪些可获取模块信息(只读)等。

 

 

五 实现细节

 

做为一个中心要实现完整的通信,通常要通过这样几个步骤:

 

创建中心角色—扫描外设(discover)—链接外设(connect)—扫描外设中的服务和特征(discover)—与外设作数据交互(explore and interact)—断开链接(disconnect)。

 

1创建中心角色

 

首先在我本身类的头文件中要包含CoreBluetooth的头文件,并继承两个协议<CBCentralManagerDelegate,CBPeripheralDelegate>,代码以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. #import <CoreBluetooth/CoreBluetooth.h>  
  2. CBCentralManager *manager;  
  3. manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];  


 

2扫描外设(discover)


代码以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. [manager scanForPeripheralsWithServices:nil options:options];  


 

这个参数应该也是能够指定特定的peripheral的UUID,那么理论上这个central只会discover这个特定的设备,可是我实际测试发现,若是用特定的UUID传参根本找不到任何设备,我用的代码以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. NSArray *uuidArray = [NSArray arrayWithObjects:[CBUUID UUIDWithString:@"1800"],[CBUUID UUIDWithString:@"180A"],  
  2. [CBUUID UUIDWithString:@"1CB2D155-33A0-EC21-6011-CD4B50710777"],[CBUUID UUIDWithString:@"6765D311-DD4C-9C14-74E1-A431BBFD0652"],nil];  
  3.        
  4. [manager scanForPeripheralsWithServices:uuidArray options:options];  

 

 

目前不清楚缘由,怀疑和设备自己在的广播包有关。

 

3链接外设(connect)

当扫描到4.0的设备后,系统会经过回调函数告诉咱们设备的信息,而后咱们就能够链接相应的设备,代码以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI  
  2. {  
  3.   
  4.     if(![_dicoveredPeripherals containsObject:peripheral])  
  5.         [_dicoveredPeripherals addObject:peripheral];  
  6.       
  7.     NSLog(@"dicoveredPeripherals:%@", _dicoveredPeripherals);  
  8. }  


 

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. //链接指定的设备  
  2. -(BOOL)connect:(CBPeripheral *)peripheral  
  3. {  
  4.     NSLog(@"connect start");  
  5.     _testPeripheral = nil;  
  6.       
  7.     [manager connectPeripheral:peripheral  
  8.                        options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];  
  9.       
  10.     //开一个定时器监控链接超时的状况  
  11.     connectTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(connectTimeout:) userInfo:peripheral repeats:NO];  
  12.   
  13.     return (YES);  
  14. }  

 

 

 

4扫描外设中的服务和特征(discover)

一样的,当链接成功后,系统会经过回调函数告诉咱们,而后咱们就在这个回调里去扫描设备下全部的服务和特征,代码以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral  
  2. {  
  3.     [connectTimer invalidate];//中止时钟  
  4.       
  5.     NSLog(@"Did connect to peripheral: %@", peripheral);  
  6.     _testPeripheral = peripheral;  
  7.       
  8.     [peripheral setDelegate:self];  
  9.     [peripheral discoverServices:nil];  
  10.       
  11.       
  12. }  

 

 

一个设备里的服务和特征每每比较多,大部分状况下咱们只是关心其中几个,因此通常会在发现服务和特征的回调里去匹配咱们关心那些,好比下面的代码:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error  
  2. {  
  3.   
  4.       
  5.     NSLog(@"didDiscoverServices");  
  6.       
  7.     if (error)  
  8.     {  
  9.         NSLog(@"Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);  
  10.           
  11.         if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectService:withPeripheral:error:)])  
  12.             [self.delegate DidNotifyFailConnectService:nil withPeripheral:nil error:nil];  
  13.           
  14.         return;  
  15.     }  
  16.       
  17.   
  18.     for (CBService *service in peripheral.services)  
  19.     {  
  20.           
  21.         if ([service.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_PROPRIETARY_SERVICE]])  
  22.         {  
  23.             NSLog(@"Service found with UUID: %@", service.UUID);  
  24.             [peripheral discoverCharacteristics:nil forService:service];  
  25.             isVPOS3356 = YES;  
  26.             break;  
  27.         }  
  28.           
  29.           
  30.     }  
  31. }  

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error   
  2. {  
  3.       
  4.     if (error)   
  5.     {  
  6.         NSLog(@"Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);  
  7.           
  8.         if ([self.delegate respondsToSelector:@selector(DidNotifyFailConnectChar:withPeripheral:error:)])  
  9.             [self.delegate DidNotifyFailConnectChar:nil withPeripheral:nil error:nil];  
  10.           
  11.         return;  
  12.     }  
  13.       
  14.       
  15.     for (CBCharacteristic *characteristic in service.characteristics)  
  16.     {  
  17.         if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_TX]])  
  18.         {  
  19.             NSLog(@"Discovered read characteristics:%@ for service: %@", characteristic.UUID, service.UUID);  
  20.               
  21.             _readCharacteristic = characteristic;//保存读的特征  
  22.               
  23.             if ([self.delegate respondsToSelector:@selector(DidFoundReadChar:)])  
  24.                 [self.delegate DidFoundReadChar:characteristic];  
  25.               
  26.             break;  
  27.         }  
  28.     }  
  29.   
  30.       
  31.     for (CBCharacteristic * characteristic in service.characteristics)  
  32.     {  
  33.           
  34.           
  35.         if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:UUIDSTR_ISSC_TRANS_RX]])  
  36.         {  
  37.   
  38.             NSLog(@"Discovered write characteristics:%@ for service: %@", characteristic.UUID, service.UUID);  
  39.             _writeCharacteristic = characteristic;//保存写的特征  
  40.               
  41.             if ([self.delegate respondsToSelector:@selector(DidFoundWriteChar:)])  
  42.                 [self.delegate DidFoundWriteChar:characteristic];  
  43.               
  44.             break;  
  45.               
  46.               
  47.         }  
  48.     }  
  49.       
  50.     if ([self.delegate respondsToSelector:@selector(DidFoundCharacteristic:withPeripheral:error:)])  
  51.         [self.delegate DidFoundCharacteristic:nil withPeripheral:nil error:nil];  
  52.       
  53. }  


相信你应该已经注意到了,回调函数都是以"did"开头的,这些函数不用你调用,达到条件后系统后自动调用。

 

 

 

5与外设作数据交互(explore and interact)

 

发送数据很简单,咱们能够封装一个以下的函数:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. //写数据  
  2. -(void)writeChar:(NSData *)data  
  3. {  
  4.     [_testPeripheral writeValue:data forCharacteristic:_writeCharacteristic type:CBCharacteristicWriteWithResponse];  
  5. }  

 


_testPeripheral和_writeCharacteristic是前面咱们保存的设备对象和能够读写的特征。

 

而后咱们能够在外部调用它,好比固然我要触发刷卡时,先组好数据包,而后调用发送函数:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. -(void)msrRead  
  2. {  
  3.       
  4.     unsigned char command[512] = {0};  
  5.     unsigned charchar *pTmp;  
  6.     int nSendLen = 0;  
  7.     unsigned char ucCrc[3] = {0};  
  8.       
  9.     _commandType = COMMAND_MSR_READ;  
  10.       
  11.     pTmp = command;  
  12.       
  13.       
  14.     *pTmp = 0x02;//start  
  15.     pTmp++;  
  16.       
  17.     *pTmp = 0xc1;//main cmd  
  18.     pTmp++;  
  19.       
  20.     *pTmp = 0x07;//sub cmd  
  21.     pTmp++;  
  22.       
  23.       
  24.       
  25.     nSendLen = 2;  
  26.       
  27.     *pTmp = nSendLen/256;  
  28.     pTmp++;  
  29.     *pTmp = nSendLen%256;  
  30.     pTmp++;  
  31.       
  32.     *pTmp = 0x00;//sub cmd  
  33.     pTmp++;  
  34.       
  35.     *pTmp = 0x00;//sub cmd  
  36.     pTmp++;  
  37.       
  38.       
  39.     Crc16CCITT(command+1,pTmp-command-1,ucCrc);  
  40.     memcpy(pTmp,ucCrc,2);  
  41.       
  42.       
  43.     NSData *data = [[NSData alloc] initWithBytes:&command length:9];  
  44.     NSLog(@"send data:%@", data);  
  45.     [g_BLEInstance.recvData setLength:0];  
  46.       
  47.     [g_BLEInstance writeChar:data];  
  48. }  


 

数据的读分为两种,一种是直接读(reading directly),另一种是订阅(subscribe)。从名字也能基本理解二者的不一样。实际使用中具体用一种要看具体的应用场景以及特征自己的属性。前一个好理解,特征自己的属性是指什么呢?特征有个properties字段(characteristic.properties),它是一个整型值,有以下几个定义:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. enum {  
  2.      CBCharacteristicPropertyBroadcast = 0x01,  
  3.      CBCharacteristicPropertyRead = 0x02,  
  4.      CBCharacteristicPropertyWriteWithoutResponse = 0x04,  
  5.      CBCharacteristicPropertyWrite = 0x08,  
  6.      CBCharacteristicPropertyNotify = 0x10,  
  7.      CBCharacteristicPropertyIndicate = 0x20,  
  8.      CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40,  
  9.      CBCharacteristicPropertyExtendedProperties = 0x80,  
  10.      };  

 


好比说,你要交互的特征,它的properties的值是0x10,表示你只能用订阅的方式来接收数据。我这里是用订阅的方式,启动订阅的代码以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. //监听设备  
  2. -(void)startSubscribe  
  3. {  
  4.     [_testPeripheral setNotifyValue:YES forCharacteristic:_readCharacteristic];  
  5. }  


 

当设备有数据返回时,一样是经过一个系统回调通知我,以下所示:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error  
  2. {  
  3.           
  4.     if (error)   
  5.     {  
  6.         NSLog(@"Error updating value for characteristic %@ error: %@", characteristic.UUID, [error localizedDescription]);  
  7.           
  8.         if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadError:)])  
  9.             [_mainMenuDelegate DidNotifyReadError:error];  
  10.           
  11.         return;  
  12.     }  
  13.       
  14.     [_recvData appendData:characteristic.value];  
  15.       
  16.       
  17.     if ([_recvData length] >= 5)//已收到长度  
  18.     {  
  19.         unsigned charchar *buffer = (unsigned charchar *)[_recvData bytes];  
  20.         int nLen = buffer[3]*256 + buffer[4];  
  21.         if ([_recvData length] == (nLen+3+2+2))  
  22.         {  
  23.             //接收完毕,通知代理作事  
  24.             if ([_mainMenuDelegate respondsToSelector:@selector(DidNotifyReadData)])  
  25.                 [_mainMenuDelegate DidNotifyReadData];  
  26.               
  27.         }  
  28.     }  
  29.   
  30. }  


 

6 断开链接(disconnect)

 

这个比较简单,只须要一个API就好了,代码以下:

 

[objc] view plain copy 在CODE上查看代码片 派生到个人代码片
  1. //主动断开设备  
  2. -(void)disConnect  
  3. {  
  4.       
  5.     if (_testPeripheral != nil)  
  6.     {  
  7.         NSLog(@"disConnect start");  
  8.         [manager cancelPeripheralConnection:_testPeripheral];  
  9.     }  
  10.   
  11. }  

 

 

六 成果展现


上几张效果图,UI没怎么修饰,主要关注功能,实现了读取磁道信息,与金融ic卡进行APDU交互等功能。

       



     


 

 /////////**********************************************************/////////

#import "ViewController.h"

#import <CoreBluetooth/CoreBluetooth.h>

#define kServiceUUID  @"3AF70026-AB81-4EF2-B90B-9C482B4812F1"

#define kCharacteristicUUID  @"2F5A22C7-7AB5-446A-9F94-4E9B924BE508"

@interface ViewController ()<CBCentralManagerDelegate, CBPeripheralDelegate>{

    CBCentralManager* _manager;

    NSMutableData* _data;

    CBPeripheral* _peripheral;

}

@end

 @implementation ViewController

- (void)viewDidLoad {

    //建立一个中央

    _manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

}

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

    if (central.state != CBCentralManagerStatePoweredOn) {

        NSLog(@"蓝牙未打开");

        return;

    }

    //开始寻找全部的服务

    [_manager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:kServiceUUID]] options:@{

                                                CBCentralManagerScanOptionAllowDuplicatesKey:@YES

                                                                                               }];

}

//寻找到服务

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

    //中止寻找

    [_manager stopScan];

    if (_peripheral != peripheral) {

        _peripheral = peripheral;

        //开始链接周边

        [_manager connectPeripheral:_peripheral options:nil];

    }

}

//链接周边成功

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

    [_data setLength:0];

    _peripheral.delegate = self;

    //链接周边服务

    [_peripheral discoverServices:@[[CBUUID UUIDWithString:kServiceUUID]]];

}

//链接周边失败

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{

    NSLog(@"链接失败");

}

//链接周边服务

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{

    if (error) {

        NSLog(@"错误的服务");

        return;

    }

    //遍历服务

    for (CBService* service in peripheral.services) {

        if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {

            //链接特征

            [_peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:kCharacteristicUUID]] forService:service];

        }

    }

}

 

//发现特征

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

    if (error) {

        NSLog(@"链接特征失败");

        return;

    }

    //遍历特征

    if ([service.UUID isEqual:[CBUUID UUIDWithString:kServiceUUID]]) {

        for (CBCharacteristic* characteristic in service.characteristics) {

            if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {

                //开始监听特征

                [_peripheral setNotifyValue:YES forCharacteristic:characteristic];

            }

        }

    }

}

//监听到特征值更新

- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

    if (error) {

        NSLog(@"特征值出错");

        return;

    }

    if (![characteristic.UUID isEqual:[CBUUID UUIDWithString:kCharacteristicUUID]]) {

        return;

    }

    //若是有新值,读取新的值

    if (characteristic.isNotifying) {

        [peripheral readValueForCharacteristic:characteristic];

    }

}

 //收到新值

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{

    NSString* str = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];

    NSLog(@"%@", str);

}

@end

 //////////////***********************//////////////////

#import "ViewController.h"

#import <CoreBluetooth/CoreBluetooth.h>

 

#define kServiceUUID  @"3AF70026-AB81-4EF2-B90B-9C482B4812F1"

#define kCharacteristicUUID  @"2F5A22C7-7AB5-446A-9F94-4E9B924BE508"

 

@interface ViewController ()<CBPeripheralManagerDelegate>{

    CBPeripheralManager* _manager;

    CBMutableService* _service;

    CBMutableCharacteristic* _characteristic;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    _manager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];

}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{

    NSLog(@"发现外设");

}

//检测中央设备状态

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral{

    if (peripheral.state != CBCentralManagerStatePoweredOn){

        NSLog(@"蓝牙关闭");

        return;

    }

    //开始中心服务

    [self startService];

}

//开始中心服务

- (void)startService{

    //经过uuid建立一个特征

    CBUUID* characteristicUUID = [CBUUID UUIDWithString:kCharacteristicUUID];

    //第一个参数uuid,第二个参数决定这个特征怎么去用,第三个是是否加密

    _characteristic = [[CBMutableCharacteristic alloc] initWithType:characteristicUUID properties:CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable];

    //建立一个服务uuid

    CBUUID* serviceUUID = [CBUUID UUIDWithString:kServiceUUID];

    //经过uuid建立服务

    _service = [[CBMutableService alloc] initWithType:serviceUUID primary:YES];

    //给服务设置特征

    [_service setCharacteristics:@[_characteristic]];

    //使用这个服务

    [_manager addService:_service];

}

//添加服务后的回调

- (void)peripheralManager:(CBPeripheralManager *)peripheral didAddService:(CBService *)service error:(NSError *)error{

    //若是没有错误,就能够开始广播服务了

    if (error == nil) {

        [_manager startAdvertising:@{

                                     CBAdvertisementDataLocalNameKey:@"PKServer",

                                     CBAdvertisementDataServiceUUIDsKey:@[[CBUUID UUIDWithString:kServiceUUID]]

                                     }];

        //[_manager updateValue:[@"pk" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_characteristic onSubscribedCentrals:]

    }

}

//有人链接成功后调用

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic{

    NSLog(@"链接成功");

    [_manager updateValue:[@"pk" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:_characteristic onSubscribedCentrals:@[central]];

}

//断开调用

- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic{

    NSLog(@"断开");

@end

相关文章
相关标签/搜索